summaryrefslogtreecommitdiffstats
path: root/x-net/src/main/java
diff options
context:
space:
mode:
Diffstat (limited to 'x-net/src/main/java')
-rw-r--r--x-net/src/main/java/javax/net/DefaultServerSocketFactory.java49
-rw-r--r--x-net/src/main/java/javax/net/DefaultSocketFactory.java60
-rw-r--r--x-net/src/main/java/javax/net/ServerSocketFactory.java109
-rw-r--r--x-net/src/main/java/javax/net/SocketFactory.java153
-rw-r--r--x-net/src/main/java/javax/net/package.html7
-rw-r--r--x-net/src/main/java/javax/net/ssl/CertPathTrustManagerParameters.java52
-rw-r--r--x-net/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java329
-rw-r--r--x-net/src/main/java/javax/net/ssl/DefaultSSLContext.java124
-rw-r--r--x-net/src/main/java/javax/net/ssl/DefaultSSLServerSocketFactory.java62
-rw-r--r--x-net/src/main/java/javax/net/ssl/DefaultSSLSocketFactory.java76
-rw-r--r--x-net/src/main/java/javax/net/ssl/HandshakeCompletedEvent.java141
-rw-r--r--x-net/src/main/java/javax/net/ssl/HandshakeCompletedListener.java34
-rw-r--r--x-net/src/main/java/javax/net/ssl/HostnameVerifier.java40
-rw-r--r--x-net/src/main/java/javax/net/ssl/HttpsURLConnection.java222
-rw-r--r--x-net/src/main/java/javax/net/ssl/KeyManager.java27
-rw-r--r--x-net/src/main/java/javax/net/ssl/KeyManagerFactory.java233
-rw-r--r--x-net/src/main/java/javax/net/ssl/KeyManagerFactorySpi.java74
-rw-r--r--x-net/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java79
-rw-r--r--x-net/src/main/java/javax/net/ssl/ManagerFactoryParameters.java27
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLContext.java253
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLContextSpi.java109
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLEngine.java464
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLEngineResult.java172
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLException.java61
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLHandshakeException.java37
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLKeyException.java36
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLPeerUnverifiedException.java38
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLPermission.java58
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLProtocolException.java37
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLServerSocket.java232
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLServerSocketFactory.java103
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSession.java231
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSessionBindingEvent.java75
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSessionBindingListener.java44
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSessionContext.java82
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSocket.java299
-rw-r--r--x-net/src/main/java/javax/net/ssl/SSLSocketFactory.java147
-rw-r--r--x-net/src/main/java/javax/net/ssl/TrustManager.java28
-rw-r--r--x-net/src/main/java/javax/net/ssl/TrustManagerFactory.java229
-rw-r--r--x-net/src/main/java/javax/net/ssl/TrustManagerFactorySpi.java67
-rw-r--r--x-net/src/main/java/javax/net/ssl/X509ExtendedKeyManager.java76
-rw-r--r--x-net/src/main/java/javax/net/ssl/X509KeyManager.java113
-rw-r--r--x-net/src/main/java/javax/net/ssl/X509TrustManager.java76
-rw-r--r--x-net/src/main/java/javax/net/ssl/package.html20
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java221
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertException.java66
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertProtocol.java286
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Appendable.java33
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java176
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java189
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateVerify.java97
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java610
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java629
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHello.java206
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientKeyExchange.java152
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java229
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionState.java169
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateSSLv3.java354
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateTLS.java352
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ContentType.java49
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DHParameters.java108
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DataStream.java42
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java65
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DigitalSignature.java254
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfBufferException.java35
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfSourceException.java34
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java374
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java82
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Handshake.java89
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java464
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java534
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HelloRequest.java77
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java137
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java133
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java186
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java122
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Message.java74
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java330
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigest.java118
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK.java117
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketFactoryImpl.java71
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketImpl.java163
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java483
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignature.java215
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java84
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java995
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImplWrapper.java203
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/PRF.java201
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java158
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLBufferedInput.java77
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLClientSessionCache.java53
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java127
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineAppData.java95
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineDataStream.java91
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineImpl.java769
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java125
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParameters.java440
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java482
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSessionCache.java52
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java366
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLStreamedInput.java57
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLv3Constants.java84
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java724
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHello.java137
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHelloDone.java78
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerKeyExchange.java193
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.java137
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java134
-rw-r--r--x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java234
109 files changed, 0 insertions, 19206 deletions
diff --git a/x-net/src/main/java/javax/net/DefaultServerSocketFactory.java b/x-net/src/main/java/javax/net/DefaultServerSocketFactory.java
deleted file mode 100644
index 9e31be4..0000000
--- a/x-net/src/main/java/javax/net/DefaultServerSocketFactory.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-
-/**
- * Default implementation of {@link javax.net.ServerSocketFactory}
- */
-final class DefaultServerSocketFactory extends ServerSocketFactory {
-
- DefaultServerSocketFactory() {
- super();
- }
-
- @Override
- public ServerSocket createServerSocket(int port) throws IOException {
- return new ServerSocket(port);
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog) throws IOException {
- return new ServerSocket(port, backlog);
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress)
- throws IOException {
- return new ServerSocket(port, backlog, iAddress);
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/DefaultSocketFactory.java b/x-net/src/main/java/javax/net/DefaultSocketFactory.java
deleted file mode 100644
index 010c720..0000000
--- a/x-net/src/main/java/javax/net/DefaultSocketFactory.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-
-/**
- * Default implementation of {@link javax.net.SocketFactory}
- */
-final class DefaultSocketFactory extends SocketFactory {
-
- DefaultSocketFactory() {
- super();
- }
-
- @Override
- public Socket createSocket() throws IOException {
- return new Socket();
- }
-
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- return new Socket(host, port);
- }
-
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- return new Socket(host, port, localHost, localPort);
- }
-
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- return new Socket(host, port);
- }
-
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException {
- return new Socket(address, port, localAddress, localPort);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ServerSocketFactory.java b/x-net/src/main/java/javax/net/ServerSocketFactory.java
deleted file mode 100644
index f2d2c0d..0000000
--- a/x-net/src/main/java/javax/net/ServerSocketFactory.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.SocketException;
-
-/**
- * This abstract class defines methods to create server sockets. It can be
- * subclassed to create specific server socket types.
- */
-public abstract class ServerSocketFactory {
- private static ServerSocketFactory defaultFactory;
-
- /**
- * Gets the default server socket factory of the system which can be used to
- * create new server sockets without creating a subclass of this factory.
- *
- * @return the system default server socket factory.
- */
- public static synchronized ServerSocketFactory getDefault() {
- if (defaultFactory == null) {
- defaultFactory = new DefaultServerSocketFactory();
- }
- return defaultFactory;
- }
-
- /**
- * Creates a new {@code ServerSocketFactory} instance.
- */
- protected ServerSocketFactory() {
- super();
- }
-
- /**
- * Creates a new server socket which is not bound to any local address. This
- * method has to be overridden by a subclass otherwise a {@code
- * SocketException} is thrown.
- *
- * @return the created unbound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
- */
- public ServerSocket createServerSocket() throws IOException {
- // follow RI's behavior
- throw new SocketException("Unbound server sockets not implemented");
- }
-
- /**
- * Creates a new server socket which is bound to the given port.
- *
- * @param port
- * the port on which the created socket has to listen.
- * @return the created bound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
- */
- public abstract ServerSocket createServerSocket(int port) throws IOException;
-
- /**
- * Creates a new server socket which is bound to the given port and
- * configures its maximum of queued connections.
- *
- * @param port
- * the port on which the created socket has to listen.
- * @param backlog
- * the maximum of queued connections.
- * @return the created bound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
- */
- public abstract ServerSocket createServerSocket(int port, int backlog) throws IOException;
-
- /**
- * Creates a new server socket which is bound to the given address on the
- * specified port and configures its maximum of queued connections.
- *
- * @param port
- * the port on which the created socket has to listen.
- * @param backlog
- * the maximum of queued connections.
- * @param iAddress
- * the address of the network interface which is used by the
- * created socket.
- * @return the created bound server socket.
- * @throws IOException
- * if an error occurs while creating a new server socket.
- */
- public abstract ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress)
- throws IOException;
-
-}
diff --git a/x-net/src/main/java/javax/net/SocketFactory.java b/x-net/src/main/java/javax/net/SocketFactory.java
deleted file mode 100644
index eb0cfcb..0000000
--- a/x-net/src/main/java/javax/net/SocketFactory.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-/**
- * This abstract class defines methods to create sockets. It can be subclassed
- * to create specific socket types with additional socket-level functionality.
- */
-public abstract class SocketFactory {
-
- private static SocketFactory defaultFactory;
-
- /**
- * Gets the default socket factory of the system which can be used to create
- * new sockets without creating a subclass of this factory.
- *
- * @return the system default socket factory.
- */
- public static synchronized SocketFactory getDefault() {
- if (defaultFactory == null) {
- defaultFactory = new DefaultSocketFactory();
- }
- return defaultFactory;
- }
-
- /**
- * Creates a new {@code SocketFactory} instance.
- */
- protected SocketFactory() {
- super();
- }
-
- /**
- * Creates a new socket which is not connected to any remote host. This
- * method has to be overridden by a subclass otherwise a {@code
- * SocketException} is thrown.
- *
- * @return the created unconnected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- */
- public Socket createSocket() throws IOException {
- // follow RI's behavior
- throw new SocketException("Unconnected sockets not implemented");
- }
-
- /**
- * Creates a new socket which is connected to the remote host specified by
- * the parameters {@code host} and {@code port}. The socket is bound to any
- * available local address and port.
- *
- * @param host
- * the remote host address the socket has to be connected to.
- * @param port
- * the port number of the remote host at which the socket is
- * connected.
- * @return the created connected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- * @throws UnknownHostException
- * if the specified host is unknown or the IP address could not
- * be resolved.
- */
- public abstract Socket createSocket(String host, int port) throws IOException,
- UnknownHostException;
-
- /**
- * Creates a new socket which is connected to the remote host specified by
- * the parameters {@code host} and {@code port}. The socket is bound to the
- * local network interface specified by the InetAddress {@code localHost} on
- * port {@code localPort}.
- *
- * @param host
- * the remote host address the socket has to be connected to.
- * @param port
- * the port number of the remote host at which the socket is
- * connected.
- * @param localHost
- * the local host address the socket is bound to.
- * @param localPort
- * the port number of the local host at which the socket is
- * bound.
- * @return the created connected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- * @throws UnknownHostException
- * if the specified host is unknown or the IP address could not
- * be resolved.
- */
- public abstract Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException;
-
- /**
- * Creates a new socket which is connected to the remote host specified by
- * the InetAddress {@code host}. The socket is bound to any available local
- * address and port.
- *
- * @param host
- * the host address the socket has to be connected to.
- * @param port
- * the port number of the remote host at which the socket is
- * connected.
- * @return the created connected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- */
- public abstract Socket createSocket(InetAddress host, int port) throws IOException;
-
-
- /**
- * Creates a new socket which is connected to the remote host specified by
- * the InetAddress {@code address}. The socket is bound to the local network
- * interface specified by the InetAddress {@code localHost} on port {@code
- * localPort}.
- *
- * @param address
- * the remote host address the socket has to be connected to.
- * @param port
- * the port number of the remote host at which the socket is
- * connected.
- * @param localAddress
- * the local host address the socket is bound to.
- * @param localPort
- * the port number of the local host at which the socket is
- * bound.
- * @return the created connected socket.
- * @throws IOException
- * if an error occurs while creating a new socket.
- */
- public abstract Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException;
-}
diff --git a/x-net/src/main/java/javax/net/package.html b/x-net/src/main/java/javax/net/package.html
deleted file mode 100644
index 5674d06..0000000
--- a/x-net/src/main/java/javax/net/package.html
+++ /dev/null
@@ -1,7 +0,0 @@
-<html>
- <body>
- <p>
- This package provides factory classes to create sockets and server-sockets. This classes can be subclassed to create factories for other kinds of socket for example the SSL-capable sockets from the package javax.net.ssl.
- </p>
- </body>
-</html>
diff --git a/x-net/src/main/java/javax/net/ssl/CertPathTrustManagerParameters.java b/x-net/src/main/java/javax/net/ssl/CertPathTrustManagerParameters.java
deleted file mode 100644
index dcf7a4d..0000000
--- a/x-net/src/main/java/javax/net/ssl/CertPathTrustManagerParameters.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.cert.CertPathParameters;
-
-/**
- * Certification path parameters to provide to certification path
- * based {@link TrustManager}.
- *
- * @since 1.5
- */
-public class CertPathTrustManagerParameters implements ManagerFactoryParameters {
-
- private final CertPathParameters param;
-
- /**
- * Creates a new {@code CertPathTrustManagerParameters} with the specified
- * certification path parameters.
- *
- * @param parameters
- * the certification path parameters.
- */
- public CertPathTrustManagerParameters(CertPathParameters parameters) {
- param = (CertPathParameters) parameters.clone();
- }
-
- /**
- * Returns a copy of the certification path parameters.
- *
- * @return a copy of the certification path parameters.
- */
- public CertPathParameters getParameters() {
- return (CertPathParameters) param.clone();
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java b/x-net/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
deleted file mode 100644
index 779c46a..0000000
--- a/x-net/src/main/java/javax/net/ssl/DefaultHostnameVerifier.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// BEGIN android-added
-// Copied and condensed code taken from the Apache HttpClient. Also slightly
-// modified, so it matches the package/class structure of the core libraries.
-// This HostnameVerifier does checking similar to what the RI and popular
-// browsers do.
-// END android-added
-
-package javax.net.ssl;
-
-import org.apache.harmony.luni.util.Inet6Util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateParsingException;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.StringTokenizer;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSocket;
-
-/**
- * A HostnameVerifier that works the same way as Curl and Firefox.
- * <p/>
- * The hostname must match either the first CN, or any of the subject-alts.
- * A wildcard can occur in the CN, and in any of the subject-alts.
- * <p/>
- * The only difference between BROWSER_COMPATIBLE and STRICT is that a wildcard
- * (such as "*.foo.com") with BROWSER_COMPATIBLE matches all subdomains,
- * including "a.b.foo.com".
- *
- * @author Julius Davies
- */
-class DefaultHostnameVerifier implements HostnameVerifier {
-
- /**
- * This contains a list of 2nd-level domains that aren't allowed to
- * have wildcards when combined with country-codes.
- * For example: [*.co.uk].
- * <p/>
- * The [*.co.uk] problem is an interesting one. Should we just hope
- * that CA's would never foolishly allow such a certificate to happen?
- * Looks like we're the only implementation guarding against this.
- * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check.
- */
- private final static String[] BAD_COUNTRY_2LDS =
- { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info",
- "lg", "ne", "net", "or", "org" };
-
- static {
- // Just in case developer forgot to manually sort the array. :-)
- Arrays.sort(BAD_COUNTRY_2LDS);
- }
-
- public DefaultHostnameVerifier() {
- super();
- }
-
- public final void verify(String host, SSLSocket ssl)
- throws IOException {
- if(host == null) {
- throw new NullPointerException("host to verify is null");
- }
-
- SSLSession session = ssl.getSession();
- Certificate[] certs = session.getPeerCertificates();
- X509Certificate x509 = (X509Certificate) certs[0];
- verify(host, x509);
- }
-
- public final boolean verify(String host, SSLSession session) {
- try {
- Certificate[] certs = session.getPeerCertificates();
- X509Certificate x509 = (X509Certificate) certs[0];
- verify(host, x509);
- return true;
- }
- catch(SSLException e) {
- return false;
- }
- }
-
- public final void verify(String host, X509Certificate cert)
- throws SSLException {
- String[] cns = getCNs(cert);
- String[] subjectAlts = getDNSSubjectAlts(cert);
- verify(host, cns, subjectAlts);
- }
-
- public final void verify(final String host, final String[] cns,
- final String[] subjectAlts,
- final boolean strictWithSubDomains)
- throws SSLException {
-
- // Build the list of names we're going to check. Our DEFAULT and
- // STRICT implementations of the HostnameVerifier only use the
- // first CN provided. All other CNs are ignored.
- // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way).
- LinkedList<String> names = new LinkedList<String>();
- if(cns != null && cns.length > 0 && cns[0] != null) {
- names.add(cns[0]);
- }
- if(subjectAlts != null) {
- for (String subjectAlt : subjectAlts) {
- if (subjectAlt != null) {
- names.add(subjectAlt);
- }
- }
- }
-
- if(names.isEmpty()) {
- String msg = "Certificate for <" + host +
- "> doesn't contain CN or DNS subjectAlt";
- throw new SSLException(msg);
- }
-
- // StringBuffer for building the error message.
- StringBuffer buf = new StringBuffer();
-
- // We're can be case-insensitive when comparing the host we used to
- // establish the socket to the hostname in the certificate.
- String hostName = host.trim().toLowerCase(Locale.ENGLISH);
- boolean match = false;
- for(Iterator<String> it = names.iterator(); it.hasNext();) {
- // Don't trim the CN, though!
- String cn = it.next();
- cn = cn.toLowerCase(Locale.ENGLISH);
- // Store CN in StringBuffer in case we need to report an error.
- buf.append(" <");
- buf.append(cn);
- buf.append('>');
- if(it.hasNext()) {
- buf.append(" OR");
- }
-
- // The CN better have at least two dots if it wants wildcard
- // action. It also can't be [*.co.uk] or [*.co.jp] or
- // [*.org.uk], etc...
- boolean doWildcard = cn.startsWith("*.") &&
- cn.lastIndexOf('.') >= 0 &&
- acceptableCountryWildcard(cn) &&
- !Inet6Util.isValidIPV4Address(host);
-
- if(doWildcard) {
- match = hostName.endsWith(cn.substring(1));
- if(match && strictWithSubDomains) {
- // If we're in strict mode, then [*.foo.com] is not
- // allowed to match [a.b.foo.com]
- match = countDots(hostName) == countDots(cn);
- }
- } else {
- match = hostName.equals(cn);
- }
- if(match) {
- break;
- }
- }
- if(!match) {
- throw new SSLException("hostname in certificate didn't match: <" +
- host + "> !=" + buf);
- }
- }
-
- public static boolean acceptableCountryWildcard(String cn) {
- int cnLen = cn.length();
- if(cnLen >= 7 && cnLen <= 9) {
- // Look for the '.' in the 3rd-last position:
- if(cn.charAt(cnLen - 3) == '.') {
- // Trim off the [*.] and the [.XX].
- String s = cn.substring(2, cnLen - 3);
- // And test against the sorted array of bad 2lds:
- int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s);
- return x < 0;
- }
- }
- return true;
- }
-
- public static String[] getCNs(X509Certificate cert) {
- LinkedList<String> cnList = new LinkedList<String>();
- /*
- Sebastian Hauer's original StrictSSLProtocolSocketFactory used
- getName() and had the following comment:
-
- Parses a X.500 distinguished name for the value of the
- "Common Name" field. This is done a bit sloppy right
- now and should probably be done a bit more according to
- <code>RFC 2253</code>.
-
- I've noticed that toString() seems to do a better job than
- getName() on these X500Principal objects, so I'm hoping that
- addresses Sebastian's concern.
-
- For example, getName() gives me this:
- 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d
-
- whereas toString() gives me this:
- EMAILADDRESS=juliusdavies@cucbc.com
-
- Looks like toString() even works with non-ascii domain names!
- I tested it with "&#x82b1;&#x5b50;.co.jp" and it worked fine.
- */
- String subjectPrincipal = cert.getSubjectX500Principal().toString();
- StringTokenizer st = new StringTokenizer(subjectPrincipal, ",");
- while(st.hasMoreTokens()) {
- String tok = st.nextToken();
- int x = tok.indexOf("CN=");
- if(x >= 0) {
- cnList.add(tok.substring(x + 3));
- }
- }
- if(!cnList.isEmpty()) {
- String[] cns = new String[cnList.size()];
- cnList.toArray(cns);
- return cns;
- } else {
- return null;
- }
- }
-
-
- /**
- * Extracts the array of SubjectAlt DNS names from an X509Certificate.
- * Returns null if there aren't any.
- * <p/>
- * Note: Java doesn't appear able to extract international characters
- * from the SubjectAlts. It can only extract international characters
- * from the CN field.
- * <p/>
- * (Or maybe the version of OpenSSL I'm using to test isn't storing the
- * international characters correctly in the SubjectAlts?).
- *
- * @param cert X509Certificate
- * @return Array of SubjectALT DNS names stored in the certificate.
- */
- public static String[] getDNSSubjectAlts(X509Certificate cert) {
- LinkedList<String> subjectAltList = new LinkedList<String>();
- Collection<List<?>> c = null;
- try {
- c = cert.getSubjectAlternativeNames();
- }
- catch(CertificateParsingException cpe) {
- Logger.getLogger(DefaultHostnameVerifier.class.getName())
- .log(Level.FINE, "Error parsing certificate.", cpe);
- }
- if(c != null) {
- for (List<?> aC : c) {
- List<?> list = aC;
- int type = ((Integer) list.get(0)).intValue();
- // If type is 2, then we've got a dNSName
- if (type == 2) {
- String s = (String) list.get(1);
- subjectAltList.add(s);
- }
- }
- }
- if(!subjectAltList.isEmpty()) {
- String[] subjectAlts = new String[subjectAltList.size()];
- subjectAltList.toArray(subjectAlts);
- return subjectAlts;
- } else {
- return null;
- }
- }
-
- /**
- * Counts the number of dots "." in a string.
- * @param s string to count dots from
- * @return number of dots
- */
- public static int countDots(final String s) {
- int count = 0;
- for(int i = 0; i < s.length(); i++) {
- if(s.charAt(i) == '.') {
- count++;
- }
- }
- return count;
- }
-
- /**
- * Checks to see if the supplied hostname matches any of the supplied CNs
- * or "DNS" Subject-Alts. Most implementations only look at the first CN,
- * and ignore any additional CNs. Most implementations do look at all of
- * the "DNS" Subject-Alts. The CNs or Subject-Alts may contain wildcards
- * according to RFC 2818.
- *
- * @param cns CN fields, in order, as extracted from the X.509
- * certificate.
- * @param subjectAlts Subject-Alt fields of type 2 ("DNS"), as extracted
- * from the X.509 certificate.
- * @param host The hostname to verify.
- * @throws SSLException If verification failed.
- */
- public final void verify(
- final String host,
- final String[] cns,
- final String[] subjectAlts) throws SSLException {
- verify(host, cns, subjectAlts, false);
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/DefaultSSLContext.java b/x-net/src/main/java/javax/net/ssl/DefaultSSLContext.java
deleted file mode 100644
index a12d385..0000000
--- a/x-net/src/main/java/javax/net/ssl/DefaultSSLContext.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.FileInputStream;
-import java.security.AccessController;
-import java.security.KeyStore;
-import java.security.PrivilegedAction;
-import java.security.Provider;
-import java.security.Security;
-
-import org.apache.harmony.security.fortress.Engine;
-import org.apache.harmony.security.fortress.Services;
-
-/**
- * Support class for this package.
- */
-final class DefaultSSLContext {
- private static SSLContext defaultSSLContext;
-
- static synchronized SSLContext getContext() {
- if (defaultSSLContext == null) {
- defaultSSLContext = AccessController
- .doPrivileged(new PrivilegedAction<SSLContext>() {
- public SSLContext run() {
- return findDefault();
- }
- });
- }
- return defaultSSLContext;
- }
-
- private static SSLContext findDefault() {
- // FIXME EXPORT CONTROL
- for (Provider provider : Services.getProvidersList()) {
- final Provider.Service service = Engine.door.getService(provider, "SSLContext");
- if (service != null) {
- try {
- SSLContext con = new SSLContext((SSLContextSpi) service.newInstance(null),
- service.getProvider(), service.getAlgorithm());
-
- /*
- * TODO
- * javax.net.ssl.keyStoreProvider,
- * javax.net.ssl.trustStoreProvider system property
- */
-
- // find KeyStore, KeyManagers
- KeyManager[] keyManagers = null;
- KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
- String keystore = System.getProperty("javax.net.ssl.keyStore");
- String keystorepwd = System.getProperty("javax.net.ssl.keyStorePassword");
- char[] pwd = null;
- if (keystorepwd != null) {
- pwd = keystorepwd.toCharArray();
- }
- if (keystore != null) {
- FileInputStream fis = new FileInputStream(keystore);
- try {
- ks.load(fis, pwd);
- } finally {
- fis.close();
- }
- KeyManagerFactory kmf;
- String kmfAlg = Security.getProperty("ssl.KeyManagerFactory.algorithm");
- if (kmfAlg == null) {
- kmfAlg = "SunX509";
- }
- kmf = KeyManagerFactory.getInstance(kmfAlg);
- kmf.init(ks, pwd);
- keyManagers = kmf.getKeyManagers();
- }
-
- // find TrustStore, TrustManagers
- TrustManager[] trustManagers = null;
- keystore = System.getProperty("javax.net.ssl.trustStore");
- keystorepwd = System.getProperty("javax.net.ssl.trustStorePassword");
- pwd = null;
- if (keystorepwd != null) {
- pwd = keystorepwd.toCharArray();
- }
- // TODO Defaults: jssecacerts; cacerts
- if (keystore != null) {
- FileInputStream fis = new FileInputStream(keystore);
- try {
- ks.load(fis, pwd);
- } finally {
- fis.close();
- }
- TrustManagerFactory tmf;
- String tmfAlg = Security.getProperty("ssl.TrustManagerFactory.algorithm");
- if (tmfAlg == null) {
- tmfAlg = "PKIX";
- }
- tmf = TrustManagerFactory.getInstance(tmfAlg);
- tmf.init(ks);
- trustManagers = tmf.getTrustManagers();
- }
-
- con.init(keyManagers, trustManagers, null);
- return con;
- } catch (Exception e) {
- // ignore and try another
- }
- }
- }
- return null;
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/DefaultSSLServerSocketFactory.java b/x-net/src/main/java/javax/net/ssl/DefaultSSLServerSocketFactory.java
deleted file mode 100644
index 3e58897..0000000
--- a/x-net/src/main/java/javax/net/ssl/DefaultSSLServerSocketFactory.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.net.SocketException;
-
-/**
- * Default inoperative implementation of javax.net.ssl.SSLServerSocketFactory
- */
-class DefaultSSLServerSocketFactory extends SSLServerSocketFactory {
-
- private final String errMessage;
-
- DefaultSSLServerSocketFactory(String mes) {
- errMessage = mes;
- }
-
- @Override
- public String[] getDefaultCipherSuites() {
- return new String[0];
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- return new String[0];
- }
-
- @Override
- public ServerSocket createServerSocket(int port) throws IOException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog) throws IOException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public ServerSocket createServerSocket(int port, int backlog, InetAddress iAddress)
- throws IOException {
- throw new SocketException(errMessage);
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/DefaultSSLSocketFactory.java b/x-net/src/main/java/javax/net/ssl/DefaultSSLSocketFactory.java
deleted file mode 100644
index 4035a0e..0000000
--- a/x-net/src/main/java/javax/net/ssl/DefaultSSLSocketFactory.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.SocketException;
-import java.net.UnknownHostException;
-
-/**
- * Default inoperative implementation of javax.net.ssl.SSLSocketFactory
- *
- */
-class DefaultSSLSocketFactory extends SSLSocketFactory {
-
- private final String errMessage;
-
- DefaultSSLSocketFactory(String mes) {
- errMessage = mes;
- }
-
- @Override
- public String[] getDefaultCipherSuites() {
- return new String[0];
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- return new String[0];
- }
-
- @Override
- public Socket createSocket(Socket s, String host, int port, boolean autoClose)
- throws IOException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public Socket createSocket(InetAddress host, int port) throws IOException {
- throw new SocketException(errMessage);
- }
-
- @Override
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
- int localPort) throws IOException {
- throw new SocketException(errMessage);
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/HandshakeCompletedEvent.java b/x-net/src/main/java/javax/net/ssl/HandshakeCompletedEvent.java
deleted file mode 100644
index 4618280..0000000
--- a/x-net/src/main/java/javax/net/ssl/HandshakeCompletedEvent.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.Serializable;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import javax.security.cert.X509Certificate;
-import java.util.EventObject;
-
-/**
- * The event object encapsulating the information about a completed SSL
- * handshake on a SSL connection.
- */
-public class HandshakeCompletedEvent extends EventObject implements Serializable {
-
- /**
- * The 5.0 spec. doesn't declare this serialVersionUID field In order to be
- * compatible it is explicitly declared here
- */
- private static final long serialVersionUID = 7914963744257769778L;
-
- private transient SSLSession session;
-
- /**
- * Creates a new {@code HandshakeCompletedEvent} with the specified SSL
- * socket and SSL session.
- *
- * @param sock
- * the SSL socket.
- * @param s
- * the SSL session.
- */
- public HandshakeCompletedEvent(SSLSocket sock, SSLSession s) {
- super(sock);
- session = s;
- }
-
- /**
- * Returns the SSL session associated with this event.
- *
- * @return the SSL session associated with this event.
- */
- public SSLSession getSession() {
- return session;
- }
-
- /**
- * Returns the name of the cipher suite negotiated during this handshake.
- *
- * @return the name of the cipher suite negotiated during this handshake.
- */
- public String getCipherSuite() {
- return session.getCipherSuite();
- }
-
- /**
- * Returns the list of local certificates used during the handshake. These
- * certificates were sent to the peer.
- *
- * @return Returns the list of certificates used during the handshake with
- * the local identity certificate followed by CAs, or {@code null}
- * if no certificates were used during the handshake.
- */
- public Certificate[] getLocalCertificates() {
- return session.getLocalCertificates();
- }
-
- /**
- * Return the list of certificates identifying the peer during the
- * handshake.
- *
- * @return the list of certificates identifying the peer with the peer's
- * identity certificate followed by CAs.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- */
- public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
- return session.getPeerCertificates();
- }
-
- /**
- * Returns the list of certificates identifying the peer. The peer's
- * identity certificate is followed by the validated certificate authority
- * certificates.
- * <p>
- * <b>Replaced by:</b> {@link #getPeerCertificates()}
- *
- * @return the list of certificates identifying the peer
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- */
- public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
- return session.getPeerCertificateChain();
- }
-
- /**
- * Returns the {@code Principal} identifying the peer.
- *
- * @return the {@code Principal} identifying the peer.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- return session.getPeerPrincipal();
- }
-
- /**
- * Returns the {@code Principal} used to identify during the handshake.
- *
- * @return the {@code Principal} used to identify during the handshake.
- */
- public Principal getLocalPrincipal() {
- return session.getLocalPrincipal();
- }
-
- /**
- * Returns the SSL socket that produced this event.
- *
- * @return the SSL socket that produced this event.
- */
- public SSLSocket getSocket() {
- return (SSLSocket) this.source;
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/HandshakeCompletedListener.java b/x-net/src/main/java/javax/net/ssl/HandshakeCompletedListener.java
deleted file mode 100644
index 5032c63..0000000
--- a/x-net/src/main/java/javax/net/ssl/HandshakeCompletedListener.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.util.EventListener;
-
-/**
- * The listener to be implemented to receive event notifications on completion
- * of SSL handshake on an SSL connection.
- */
-public interface HandshakeCompletedListener extends EventListener {
- /**
- * The callback method that is invoked when a SSL handshake is completed.
- *
- * @param event
- * the information on the completed SSL handshake event.
- */
- void handshakeCompleted(HandshakeCompletedEvent event);
-}
diff --git a/x-net/src/main/java/javax/net/ssl/HostnameVerifier.java b/x-net/src/main/java/javax/net/ssl/HostnameVerifier.java
deleted file mode 100644
index 805762e..0000000
--- a/x-net/src/main/java/javax/net/ssl/HostnameVerifier.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The interface to be used to provide hostname verification functionality.
- * <p>
- * This is an extended verification option that implementers can provide. It is to be used
- * during a handshake if the URL's hostname does not match the peer's
- * identification hostname.
- */
-public interface HostnameVerifier {
- /**
- * Verifies that the specified hostname is allowed within the specified SSL
- * session.
- *
- * @param hostname
- * the hostname.
- * @param session
- * the SSL session of the connection.
- * @return {@code true} if the specified hostname is allowed, otherwise
- * {@code false}.
- */
- boolean verify(String hostname, SSLSession session);
-}
diff --git a/x-net/src/main/java/javax/net/ssl/HttpsURLConnection.java b/x-net/src/main/java/javax/net/ssl/HttpsURLConnection.java
deleted file mode 100644
index 8c49690..0000000
--- a/x-net/src/main/java/javax/net/ssl/HttpsURLConnection.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.net.HttpURLConnection;
-import java.net.URL;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-
-/**
- * This abstract subclass of {@code HttpURLConnection} defines methods for
- * managing HTTPS connections according to the description given by RFC 2818.
- */
-public abstract class HttpsURLConnection extends HttpURLConnection {
-
- private static HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();
-
- private static SSLSocketFactory defaultSSLSocketFactory = (SSLSocketFactory) SSLSocketFactory
- .getDefault();
-
- /**
- * Sets the default hostname verifier to be used by new instances.
- *
- * @param v
- * the new default hostname verifier
- * @throws IllegalArgumentException
- * if the specified verifier is {@code null}.
- */
- public static void setDefaultHostnameVerifier(HostnameVerifier v) {
- if (v == null) {
- throw new IllegalArgumentException("HostnameVerifier is null");
- }
- defaultHostnameVerifier = v;
- }
-
- /**
- * Returns the default hostname verifier.
- *
- * @return the default hostname verifier.
- */
- public static HostnameVerifier getDefaultHostnameVerifier() {
- return defaultHostnameVerifier;
- }
-
- /**
- * Sets the default SSL socket factory to be used by new instances.
- *
- * @param sf
- * the new default SSL socket factory.
- * @throws IllegalArgumentException
- * if the specified socket factory is {@code null}.
- */
- public static void setDefaultSSLSocketFactory(SSLSocketFactory sf) {
- if (sf == null) {
- throw new IllegalArgumentException("SSLSocketFactory is null");
- }
- defaultSSLSocketFactory = sf;
- }
-
- /**
- * Returns the default SSL socket factory for new instances.
- *
- * @return the default SSL socket factory for new instances.
- */
- public static SSLSocketFactory getDefaultSSLSocketFactory() {
- return defaultSSLSocketFactory;
- }
-
- /**
- * The host name verifier used by this connection. It is initialized from
- * the default hostname verifier
- * {@link #setDefaultHostnameVerifier(HostnameVerifier)} or
- * {@link #getDefaultHostnameVerifier()}.
- */
- protected HostnameVerifier hostnameVerifier;
-
- private SSLSocketFactory sslSocketFactory;
-
- /**
- * Creates a new {@code HttpsURLConnection} with the specified {@code URL}.
- *
- * @param url
- * the {@code URL} to connect to.
- */
- protected HttpsURLConnection(URL url) {
- super(url);
- hostnameVerifier = defaultHostnameVerifier;
- sslSocketFactory = defaultSSLSocketFactory;
- }
-
- /**
- * Returns the name of the cipher suite negotiated during the SSL handshake.
- *
- * @return the name of the cipher suite negotiated during the SSL handshake.
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public abstract String getCipherSuite();
-
- /**
- * Returns the list of local certificates used during the handshake. These
- * certificates were sent to the peer.
- *
- * @return Returns the list of certificates used during the handshake with
- * the local identity certificate followed by CAs, or {@code null}
- * if no certificates were used during the handshake.
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public abstract Certificate[] getLocalCertificates();
-
- /**
- * Return the list of certificates identifying the peer during the
- * handshake.
- *
- * @return the list of certificates identifying the peer with the peer's
- * identity certificate followed by CAs.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified..
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public abstract Certificate[] getServerCertificates() throws SSLPeerUnverifiedException;
-
- /**
- * Returns the {@code Principal} identifying the peer.
- *
- * @return the {@code Principal} identifying the peer.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- Certificate[] certs = getServerCertificates();
- if (certs == null || certs.length == 0 || (!(certs[0] instanceof X509Certificate))) {
- throw new SSLPeerUnverifiedException("No server's end-entity certificate");
- }
- return ((X509Certificate) certs[0]).getSubjectX500Principal();
- }
-
- /**
- * Returns the {@code Principal} used to identify the local host during the handshake.
- *
- * @return the {@code Principal} used to identify the local host during the handshake, or
- * {@code null} if none was used.
- * @throws IllegalStateException
- * if no connection has been established yet.
- */
- public Principal getLocalPrincipal() {
- Certificate[] certs = getLocalCertificates();
- if (certs == null || certs.length == 0 || (!(certs[0] instanceof X509Certificate))) {
- return null;
- }
- return ((X509Certificate) certs[0]).getSubjectX500Principal();
- }
-
- /**
- * Sets the hostname verifier for this instance.
- *
- * @param v
- * the hostname verifier for this instance.
- * @throws IllegalArgumentException
- * if the specified verifier is {@code null}.
- */
- public void setHostnameVerifier(HostnameVerifier v) {
- if (v == null) {
- throw new IllegalArgumentException("HostnameVerifier is null");
- }
- hostnameVerifier = v;
- }
-
- /**
- * Returns the hostname verifier used by this instance.
- *
- * @return the hostname verifier used by this instance.
- */
- public HostnameVerifier getHostnameVerifier() {
- return hostnameVerifier;
- }
-
- /**
- * Sets the SSL socket factory for this instance.
- *
- * @param sf
- * the SSL socket factory to be used by this instance.
- * @throws IllegalArgumentException
- * if the specified socket factory is {@code null}.
- */
- public void setSSLSocketFactory(SSLSocketFactory sf) {
- if (sf == null) {
- throw new IllegalArgumentException("SSLSocketFactory is null");
- }
- sslSocketFactory = sf;
- }
-
- /**
- * Returns the SSL socket factory used by this instance.
- *
- * @return the SSL socket factory used by this instance.
- */
- public SSLSocketFactory getSSLSocketFactory() {
- return sslSocketFactory;
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/KeyManager.java b/x-net/src/main/java/javax/net/ssl/KeyManager.java
deleted file mode 100644
index 30c8032..0000000
--- a/x-net/src/main/java/javax/net/ssl/KeyManager.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * This is the interface to implement in order to mark a class as a JSSE key
- * managers so that key managers can be easily grouped. The key managers are
- * responsible for handling the keys used to authenticate the local side to its
- * peer,
- */
-public interface KeyManager {
-}
diff --git a/x-net/src/main/java/javax/net/ssl/KeyManagerFactory.java b/x-net/src/main/java/javax/net/ssl/KeyManagerFactory.java
deleted file mode 100644
index 99a37a8..0000000
--- a/x-net/src/main/java/javax/net/ssl/KeyManagerFactory.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivilegedAction;
-import java.security.Provider;
-import java.security.Security;
-import java.security.UnrecoverableKeyException;
-
-import org.apache.harmony.security.fortress.Engine;
-
-/**
- * The public API for {@code KeyManagerFactory} implementations.
- */
-public class KeyManagerFactory {
- // Store KeyManagerFactory service name
- private static final String SERVICE = "KeyManagerFactory";
-
- // Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
-
- // Store default property name
- private static final String PROPERTY_NAME = "ssl.KeyManagerFactory.algorithm";
-
- /**
- * Returns the default key manager factory algorithm name.
- * <p>
- * The default algorithm name is specified by the security property:
- * {@code 'ssl.KeyManagerFactory.algorithm'}.
- *
- * @return the default algorithm name.
- */
- public static final String getDefaultAlgorithm() {
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTY_NAME);
- }
- });
- }
-
- /**
- * Creates a new {@code KeyManagerFactory} instance for the specified key
- * management algorithm.
- *
- * @param algorithm
- * the name of the requested key management algorithm.
- * @return a key manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if no installed provider can provide the requested algorithm.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final KeyManagerFactory getInstance(String algorithm)
- throws NoSuchAlgorithmException {
- if (algorithm == null) {
- throw new NullPointerException("algorithm is null");
- }
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new KeyManagerFactory((KeyManagerFactorySpi) engine.spi, engine.provider,
- algorithm);
- }
- }
-
- /**
- * Creates a new {@code KeyManagerFactory} instance for the specified key
- * management algorithm from the specified provider.
- *
- * @param algorithm
- * the name of the requested key management algorithm name.
- * @param provider
- * the name of the provider that provides the requested
- * algorithm.
- * @return a key manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * algorithm.
- * @throws NoSuchProviderException
- * if the specified provider does not exist.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final KeyManagerFactory getInstance(String algorithm, String provider)
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if ((provider == null) || (provider.length() == 0)) {
- throw new IllegalArgumentException("Provider is null or empty");
- }
- Provider impProvider = Security.getProvider(provider);
- if (impProvider == null) {
- throw new NoSuchProviderException(provider);
- }
- return getInstance(algorithm, impProvider);
- }
-
- /**
- * Creates a new {@code KeyManagerFactory} instance for the specified key
- * management algorithm from the specified provider.
- *
- * @param algorithm
- * the name of the requested key management algorithm name.
- * @param provider
- * the provider that provides the requested algorithm.
- * @return a key manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * algorithm.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final KeyManagerFactory getInstance(String algorithm, Provider provider)
- throws NoSuchAlgorithmException {
- if (provider == null) {
- throw new IllegalArgumentException("Provider is null");
- }
- if (algorithm == null) {
- throw new NullPointerException("algorithm is null");
- }
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new KeyManagerFactory((KeyManagerFactorySpi) engine.spi, provider, algorithm);
- }
- }
-
- // Store used provider
- private final Provider provider;
-
- // Store used KeyManagerFactorySpi implementation
- private final KeyManagerFactorySpi spiImpl;
-
- // Store used algorithm
- private final String algorithm;
-
- /**
- * Creates a new {@code KeyManagerFactory}.
- *
- * @param factorySpi
- * the implementation delegate.
- * @param provider
- * the provider.
- * @param algorithm
- * the key management algorithm name.
- */
- protected KeyManagerFactory(KeyManagerFactorySpi factorySpi, Provider provider, String algorithm) {
- super();
- this.provider = provider;
- this.algorithm = algorithm;
- this.spiImpl = factorySpi;
- }
-
- /**
- * Returns the name of the key management algorithm.
- *
- * @return the name of the key management algorithm.
- */
- public final String getAlgorithm() {
- return algorithm;
- }
-
- /**
- * Returns the provider for this {@code KeyManagerFactory} instance.
- *
- * @return the provider for this {@code KeyManagerFactory} instance.
- */
- public final Provider getProvider() {
- return provider;
- }
-
- /**
- * Initializes this instance with the specified key store and password.
- *
- * @param ks
- * the key store or {@code null} to use the default key store.
- * @param password
- * the password for the specified key store or {@code null} if no
- * key store is provided.
- * @throws KeyStoreException
- * if initializing this key manager factory fails.
- * @throws NoSuchAlgorithmException
- * if a required algorithm is not available.
- * @throws UnrecoverableKeyException
- * if a key cannot be recovered.
- */
- public final void init(KeyStore ks, char[] password) throws KeyStoreException,
- NoSuchAlgorithmException, UnrecoverableKeyException {
- spiImpl.engineInit(ks, password);
- }
-
- /**
- * Initializes this instance with the specified factory parameters.
- *
- * @param spec
- * the factory parameters.
- * @throws InvalidAlgorithmParameterException
- * if an error occurs.
- */
- public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException {
- spiImpl.engineInit(spec);
- }
-
- /**
- * Returns a list of key managers, one instance for each type of key in the
- * key store.
- *
- * @return a list of key managers.
- */
- public final KeyManager[] getKeyManagers() {
- return spiImpl.engineGetKeyManagers();
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/KeyManagerFactorySpi.java b/x-net/src/main/java/javax/net/ssl/KeyManagerFactorySpi.java
deleted file mode 100644
index 39925f9..0000000
--- a/x-net/src/main/java/javax/net/ssl/KeyManagerFactorySpi.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-
-/**
- * The <i>Service Provider Interface</i> (SPI) for the
- * {@code KeyManagerFactory} class.
- */
-public abstract class KeyManagerFactorySpi {
-
- /**
- * Creates a new {@code KeyManagerFactorySpi} instance.
- */
- public KeyManagerFactorySpi() {
- super();
- }
-
- /**
- * Initializes this instance with the specified key store and password.
- *
- * @param ks
- * the key store or {@code null} to use the default key store.
- * @param password
- * the key store password.
- * @throws KeyStoreException
- * if initializing this instance fails.
- * @throws NoSuchAlgorithmException
- * if a required algorithm is not available.
- * @throws UnrecoverableKeyException
- * if a key cannot be recovered.
- */
- protected abstract void engineInit(KeyStore ks, char[] password) throws KeyStoreException,
- NoSuchAlgorithmException, UnrecoverableKeyException;
-
- /**
- * Initializes this instance with the specified factory parameters.
- *
- * @param spec
- * the factory parameters.
- * @throws InvalidAlgorithmParameterException
- * if an error occurs.
- */
- protected abstract void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException;
-
- /**
- * Returns a list of key managers, one instance for each type of key in the
- * key store.
- *
- * @return a list of key managers.
- */
- protected abstract KeyManager[] engineGetKeyManagers();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java b/x-net/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java
deleted file mode 100644
index d30cc8a..0000000
--- a/x-net/src/main/java/javax/net/ssl/KeyStoreBuilderParameters.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.security.KeyStore;
-
-/**
- * The parameters for {@code KeyManager}s. The parameters are a list of
- * {@code KeyStore.Builder}s.
- *
- * @since 1.5
- * @see KeyStore.Builder
- */
-public class KeyStoreBuilderParameters implements ManagerFactoryParameters {
-
- private final List<KeyStore.Builder> ksbuilders;
-
- /**
- * Creates a new {@code KeyStoreBuilderParameters} with the specified key
- * store builder.
- *
- * @param builder
- * the key store builder.
- */
- public KeyStoreBuilderParameters(KeyStore.Builder builder) {
- super();
- ksbuilders = Collections.singletonList(builder);
- }
-
- /**
- * Creates a new {@code KeyStoreBuilderParameters} with the specified list
- * of {@code KeyStore.Builder}s.
- *
- * @param parameters
- * the list of key store builders
- * @throws IllegalArgumentException
- * if the specified list is empty.
- */
- @SuppressWarnings("unchecked")
- public KeyStoreBuilderParameters(List parameters) {
- super();
- if (parameters == null) {
- throw new NullPointerException("Builders list is null");
- }
- if (parameters.isEmpty()) {
- throw new IllegalArgumentException("Builders list is empty");
- }
- ksbuilders = Collections.unmodifiableList(new ArrayList<KeyStore.Builder>(parameters));
- }
-
- /**
- * Returns the unmodifiable list of {@code KeyStore.Builder}s associated
- * with this parameters instance.
- *
- * @return the unmodifiable list of {@code KeyStore.Builder}s.
- */
- @SuppressWarnings("unchecked")
- public List getParameters() {
- return ksbuilders;
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/ManagerFactoryParameters.java b/x-net/src/main/java/javax/net/ssl/ManagerFactoryParameters.java
deleted file mode 100644
index b90deeb..0000000
--- a/x-net/src/main/java/javax/net/ssl/ManagerFactoryParameters.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The marker interface for key manager factory parameters. Its purpose is to
- * group key manager factory parameters objects.
- *
- * @since 1.4
- */
-public interface ManagerFactoryParameters {
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLContext.java b/x-net/src/main/java/javax/net/ssl/SSLContext.java
deleted file mode 100644
index 8a0a157..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLContext.java
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.KeyManagementException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.Provider;
-import java.security.SecureRandom;
-import java.security.Security;
-
-import org.apache.harmony.security.fortress.Engine;
-
-
-/**
- * The public API for secure socket protocol implementations. It acts as factory
- * for {@code SSLSocketFactory}'s and {@code SSLEngine}s.
- */
-public class SSLContext {
- // StoreSSLContext service name
- private static final String SERVICE = "SSLContext";
-
- // Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
-
- /**
- * Creates a new {@code SSLContext} instance for the specified protocol.
- *
- * @param protocol
- * the requested protocol to create a context for.
- * @return the created {@code SSLContext} instance.
- * @throws NoSuchAlgorithmException
- * if no installed provider can provide the requested protocol
- * @throws NullPointerException
- * if {@code protocol} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static SSLContext getInstance(String protocol) throws NoSuchAlgorithmException {
- if (protocol == null) {
- throw new NullPointerException("protocol is null");
- }
- synchronized (engine) {
- engine.getInstance(protocol, null);
- return new SSLContext((SSLContextSpi) engine.spi, engine.provider, protocol);
- }
- }
-
- /**
- * Creates a new {@code SSLContext} instance for the specified protocol from
- * the specified provider.
- *
- * @param protocol
- * the requested protocol to create a context for.
- * @param provider
- * the name of the provider that provides the requested protocol.
- * @return an {@code SSLContext} for the requested protocol.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provider the requested
- * protocol.
- * @throws NoSuchProviderException
- * if the specified provider does not exits.
- * @throws NullPointerException
- * if {@code protocol} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static SSLContext getInstance(String protocol, String provider)
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if (provider == null) {
- throw new IllegalArgumentException("Provider is null");
- }
- if (provider.length() == 0) {
- throw new IllegalArgumentException("Provider is empty");
- }
- Provider impProvider = Security.getProvider(provider);
- if (impProvider == null) {
- throw new NoSuchProviderException(provider);
- }
- return getInstance(protocol, impProvider);
- }
-
- /**
- * Creates a new {@code SSLContext} instance for the specified protocol from
- * the specified provider.
- *
- * @param protocol
- * the requested protocol to create a context for
- * @param provider
- * the provider that provides the requested protocol.
- * @return an {@code SSLContext} for the requested protocol.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * protocol.
- * @throws NullPointerException
- * if {@code protocol} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static SSLContext getInstance(String protocol, Provider provider)
- throws NoSuchAlgorithmException {
- if (provider == null) {
- throw new IllegalArgumentException("provider is null");
- }
- if (protocol == null) {
- throw new NullPointerException("protocol is null");
- }
- synchronized (engine) {
- engine.getInstance(protocol, provider, null);
- return new SSLContext((SSLContextSpi) engine.spi, provider, protocol);
- }
- }
-
- private final Provider provider;
-
- private final SSLContextSpi spiImpl;
-
- private final String protocol;
-
- /**
- * Creates a new {@code SSLContext}.
- *
- * @param contextSpi
- * the implementation delegate.
- * @param provider
- * the provider.
- * @param protocol
- * the protocol name.
- */
- protected SSLContext(SSLContextSpi contextSpi, Provider provider, String protocol) {
- this.provider = provider;
- this.protocol = protocol;
- this.spiImpl = contextSpi;
- }
-
- /**
- * Returns the name of the secure socket protocol of this instance.
- *
- * @return the name of the secure socket protocol of this instance.
- */
- public final String getProtocol() {
- return protocol;
- }
-
- /**
- * Returns the provider of this {@code SSLContext} instance.
- *
- * @return the provider of this {@code SSLContext} instance.
- */
- public final Provider getProvider() {
- return provider;
- }
-
- /**
- * Initializes this {@code SSLContext} instance. All of the arguments are
- * optional, and the security providers will be searched for the required
- * implementations of the needed algorithms.
- *
- * @param km
- * the key sources or {@code null}.
- * @param tm
- * the trust decision sources or {@code null}.
- * @param sr
- * the randomness source or {@code null.}
- * @throws KeyManagementException
- * if initializing this instance fails.
- */
- public final void init(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
- throws KeyManagementException {
- spiImpl.engineInit(km, tm, sr);
- }
-
- /**
- * Returns a socket factory for this instance.
- *
- * @return a socket factory for this instance.
- */
- public final SSLSocketFactory getSocketFactory() {
- return spiImpl.engineGetSocketFactory();
- }
-
- /**
- * Returns a server socket factory for this instance.
- *
- * @return a server socket factory for this instance.
- */
- public final SSLServerSocketFactory getServerSocketFactory() {
- return spiImpl.engineGetServerSocketFactory();
- }
-
- /**
- * Creates an {@code SSLEngine} instance from this context.
- *
- * @return an {@code SSLEngine} instance from this context.
- * @throws UnsupportedOperationException
- * if the provider does not support the operation.
- */
- public final SSLEngine createSSLEngine() {
- return spiImpl.engineCreateSSLEngine();
- }
-
- /**
- * Creates an {@code SSLEngine} instance from this context with the
- * specified hostname and port.
- *
- * @param peerHost
- * the name of the host
- * @param peerPort
- * the port
- * @return an {@code SSLEngine} instance from this context.
- * @throws UnsupportedOperationException
- * if the provider does not support the operation.
- */
- public final SSLEngine createSSLEngine(String peerHost, int peerPort) {
- return spiImpl.engineCreateSSLEngine(peerHost, peerPort);
- }
-
- /**
- * Returns the SSL session context that encapsulates the set of SSL sessions
- * that can be used for handshake of server-side SSL sockets.
- *
- * @return the SSL server session context for this context or {@code null}
- * if the underlying provider does not provide an implementation of
- * the {@code SSLSessionContext} interface.
- */
- public final SSLSessionContext getServerSessionContext() {
- return spiImpl.engineGetServerSessionContext();
- }
-
- /**
- * Returns the SSL session context that encapsulates the set of SSL sessions
- * that can be used for handshake of client-side SSL sockets.
- *
- * @return the SSL client session context for this context or {@code null}
- * if the underlying provider does not provide an implementation of
- * the {@code SSLSessionContext} interface.
- */
- public final SSLSessionContext getClientSessionContext() {
- return spiImpl.engineGetClientSessionContext();
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLContextSpi.java b/x-net/src/main/java/javax/net/ssl/SSLContextSpi.java
deleted file mode 100644
index 44d2c59..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLContextSpi.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.KeyManagementException;
-import java.security.SecureRandom;
-
-/**
- * The <i>Service Provider Interface</i> (SPI) for the {@code SSLContext} class.
- */
-public abstract class SSLContextSpi {
-
- /**
- * Creates a new {@code SSLContextSpi} instance.
- */
- public SSLContextSpi() {
- super();
- }
-
- /**
- * Initializes this {@code SSLContext} instance. All of the arguments are
- * optional, and the security providers will be searched for the required
- * implementations of the needed algorithms.
- *
- * @param km
- * the key sources or {@code null}.
- * @param tm
- * the trust decision sources or {@code null}.
- * @param sr
- * the randomness source or {@code null.}
- * @throws KeyManagementException
- * if initializing this instance fails.
- */
- protected abstract void engineInit(KeyManager[] km, TrustManager[] tm, SecureRandom sr)
- throws KeyManagementException;
-
- /**
- * Returns a socket factory for this instance.
- *
- * @return a socket factory for this instance.
- */
- protected abstract SSLSocketFactory engineGetSocketFactory();
-
- /**
- * Returns a server socket factory for this instance.
- *
- * @return a server socket factory for this instance.
- */
- protected abstract SSLServerSocketFactory engineGetServerSocketFactory();
-
- /**
- * Creates an {@code SSLEngine} instance from this context with the
- * specified hostname and port.
- *
- * @param host
- * the name of the host
- * @param port
- * the port
- * @return an {@code SSLEngine} instance from this context.
- * @throws UnsupportedOperationException
- * if the provider does not support the operation.
- */
- protected abstract SSLEngine engineCreateSSLEngine(String host, int port);
-
- /**
- * Creates an {@code SSLEngine} instance from this context.
- *
- * @return an {@code SSLEngine} instance from this context.
- * @throws UnsupportedOperationException
- * if the provider does not support the operation.
- */
- protected abstract SSLEngine engineCreateSSLEngine();
-
- /**
- * Returns the SSL session context that encapsulates the set of SSL sessions
- * that can be used for the server side of the SSL handshake.
- *
- * @return the SSL server session context for this context or {@code null}
- * if the underlying provider does not provide an implementation of
- * the {@code SSLSessionContext} interface.
- */
- protected abstract SSLSessionContext engineGetServerSessionContext();
-
- /**
- * Returns the SSL session context that encapsulates the set of SSL sessions
- * that can be used for the client side of the SSL handshake.
- *
- * @return the SSL client session context for this context or {@code null}
- * if the underlying provider does not provide an implementation of
- * the {@code SSLSessionContext} interface.
- */
- protected abstract SSLSessionContext engineGetClientSessionContext();
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLEngine.java b/x-net/src/main/java/javax/net/ssl/SSLEngine.java
deleted file mode 100644
index 46e11a4..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLEngine.java
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.nio.ByteBuffer;
-
-/**
- * The abstract implementation of secure communications using SSL, TLS, or other
- * protocols. It includes the setup, handshake, and encrypt/decrypt
- * functionality needed to create a secure connection.
- *
- * @since 1.5
- */
-public abstract class SSLEngine {
- private final String peerHost;
- private final int peerPort;
-
- /**
- * Creates a new {@code SSLEngine} instance.
- */
- protected SSLEngine() {
- super();
- peerHost = null;
- peerPort = -1;
- }
-
- /**
- * Creates a new {@code SSLEngine} instance with the specified host and
- * port.
- *
- * @param host
- * the name of the host.
- * @param port
- * the port of the host.
- */
- protected SSLEngine(String host, int port) {
- super();
- this.peerHost = host;
- this.peerPort = port;
- }
-
- /**
- * Returns the name of the peer host.
- *
- * @return the name of the peer host, or {@code null} if none is available.
- */
- public String getPeerHost() {
- return peerHost;
- }
-
- /**
- * Returns the port number of the peer host.
- *
- * @return the port number of the peer host, or {@code -1} is none is
- * available.
- */
- public int getPeerPort() {
- return peerPort;
- }
-
- /**
- * Initiates a handshake on this engine.
- * <p>
- * Calling this method is not needed for the initial handshake: it will be
- * called by {@code wrap} or {@code unwrap} if the initial handshake has not
- * been started yet.
- *
- * @throws SSLException
- * if starting the handshake fails.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public abstract void beginHandshake() throws SSLException;
-
- /**
- * Notifies this engine instance that no more inbound network data will be
- * sent to this engine.
- *
- * @throws SSLException
- * if this engine did not receive a needed protocol specific
- * close notification message from the peer.
- */
- public abstract void closeInbound() throws SSLException;
-
- /**
- * Notifies this engine instance that no more outbound application data will
- * be sent to this engine.
- */
- public abstract void closeOutbound();
-
- /**
- * Returns a delegate task for this engine instance. Some engine operations
- * may require the results of blocking or long running operations, and the
- * {@code SSLEngineResult} instances returned by this engine may indicate
- * that a delegated task result is needed. In this case the
- * {@link Runnable#run() run} method of the returned {@code Runnable}
- * delegated task must be called.
- *
- * @return a delegate task, or {@code null} if none are available.
- */
- public abstract Runnable getDelegatedTask();
-
- /**
- * Returns the SSL cipher suite names that are enabled in this engine
- * instance.
- *
- * @return the SSL cipher suite names that are enabled in this engine
- * instance.
- */
- public abstract String[] getEnabledCipherSuites();
-
- /**
- * Returns the protocol version names that are enabled in this engine
- * instance.
- *
- * @return the protocol version names that are enabled in this engine
- * instance.
- */
- public abstract String[] getEnabledProtocols();
-
- /**
- * Returns whether new SSL sessions may be established by this engine.
- *
- * @return {@code true} if new session may be established, {@code false} if
- * existing sessions must be reused.
- */
- public abstract boolean getEnableSessionCreation();
-
- /**
- * Returns the status of the handshake of this engine instance.
- *
- * @return the status of the handshake of this engine instance.
- */
- public abstract SSLEngineResult.HandshakeStatus getHandshakeStatus();
-
- /**
- * Returns whether this engine instance will require client authentication.
- *
- * @return {@code true} if this engine will require client authentication,
- * {@code false} if no client authentication is needed.
- */
- public abstract boolean getNeedClientAuth();
-
- /**
- * Returns the SSL session for this engine instance.
- *
- * @return the SSL session for this engine instance.
- */
- public abstract SSLSession getSession();
-
- /**
- * Returns the SSL cipher suite names that are supported by this engine.
- * These cipher suites can be enabled using
- * {@link #setEnabledCipherSuites(String[])}.
- *
- * @return the SSL cipher suite names that are supported by this engine.
- */
- public abstract String[] getSupportedCipherSuites();
-
- /**
- * Returns the protocol names that are supported by this engine. These
- * protocols can be enables using {@link #setEnabledProtocols(String[])}.
- *
- * @return the protocol names that are supported by this engine.
- */
- public abstract String[] getSupportedProtocols();
-
- /**
- * Returns whether this engine is set to act in client mode when
- * handshaking.
- *
- * @return {@code true} if the engine is set to do handshaking in client
- * mode.
- */
- public abstract boolean getUseClientMode();
-
- /**
- * Returns whether this engine will request client authentication.
- *
- * @return {@code true} if client authentication will be requested,
- * {@code false} otherwise.
- */
- public abstract boolean getWantClientAuth();
-
- /**
- * Returns whether no more inbound data will be accepted by this engine.
- *
- * @return {@code true} if no more inbound data will be accepted by this
- * engine, {@code false} otherwise.
- */
- public abstract boolean isInboundDone();
-
- /**
- * Returns whether no more outbound data will be produced by this engine.
- *
- * @return {@code true} if no more outbound data will be producted by this
- * engine, {@code otherwise} false.
- */
- public abstract boolean isOutboundDone();
-
- /**
- * Sets the SSL cipher suite names that should be enabled in this engine
- * instance. Only cipher suites listed by {@code getSupportedCipherSuites()}
- * are allowed.
- *
- * @param suites
- * the SSL cipher suite names to be enabled.
- * @throws IllegalArgumentException
- * if one of the specified cipher suites is not supported, or if
- * {@code suites} is {@code null}.
- */
- public abstract void setEnabledCipherSuites(String[] suites);
-
- /**
- * Sets the protocol version names that should be enabled in this engine
- * instance. Only protocols listed by {@code getSupportedProtocols()} are
- * allowed.
- *
- * @param protocols
- * the protocol version names to be enabled.
- * @throws IllegalArgumentException
- * if one of the protocol version names is not supported, or if
- * {@code protocols} is {@code null}.
- */
- public abstract void setEnabledProtocols(String[] protocols);
-
- /**
- * Sets whether new SSL sessions may be established by this engine instance.
- *
- * @param flag
- * {@code true} if new SSL sessions may be established,
- * {@code false} if existing SSL sessions must be reused.
- */
- public abstract void setEnableSessionCreation(boolean flag);
-
- /**
- * Sets whether this engine must require client authentication. The client
- * authentication is one of:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setWantClientAuth(boolean)}.
- *
- * @param need
- * {@code true} if client authentication is required,
- * {@code false} if no authentication is needed.
- */
- public abstract void setNeedClientAuth(boolean need);
-
- /**
- * Sets whether this engine should act in client (or server) mode when
- * handshaking.
- *
- * @param mode
- * {@code true} if this engine should act in client mode,
- * {@code false} if not.
- * @throws IllegalArgumentException
- * if this method is called after starting the initial
- * handshake.
- */
- public abstract void setUseClientMode(boolean mode);
-
- /**
- * Sets whether this engine should request client authentication. The client
- * authentication is one of the following:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setNeedClientAuth(boolean)}.
- *
- * @param want
- * {@code true} if client authentication should be requested,
- * {@code false} if no authentication is needed.
- */
- public abstract void setWantClientAuth(boolean want);
-
- /**
- * Decodes the incoming network data buffer into application data buffers.
- * If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param src
- * the buffer with incoming network data
- * @param dsts
- * the array of destination buffers for incoming application
- * data.
- * @param offset
- * the offset in the array of destination buffers to which data
- * is to be transferred.
- * @param length
- * the maximum number of destination buffers to be used.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws IndexOutOfBoundsException
- * if {@code length} is greater than
- * {@code dsts.length - offset}.
- * @throws java.nio.ReadOnlyBufferException
- * if one of the destination buffers is read-only.
- * @throws IllegalArgumentException
- * if {@code src}, {@code dsts}, or one of the entries in
- * {@code dsts} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public abstract SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length)
- throws SSLException;
-
- /**
- * Encodes the outgoing application data buffers into the network data
- * buffer. If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param srcs
- * the array of source buffers of outgoing application data.
- * @param offset
- * the offset in the array of source buffers from which data is
- * to be retrieved.
- * @param length
- * the maximum number of source buffers to be used.
- * @param dst
- * the destination buffer for network data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws IndexOutOfBoundsException
- * if {@code length} is greater than
- * {@code srcs.length - offset}.
- * @throws java.nio.ReadOnlyBufferException
- * if the destination buffer is readonly.
- * @throws IllegalArgumentException
- * if {@code srcs}, {@code dst}, or one the entries in
- * {@code srcs} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public abstract SSLEngineResult wrap(ByteBuffer[] srcs, int offset, int length, ByteBuffer dst)
- throws SSLException;
-
- /**
- * Decodes the incoming network data buffer into the application data
- * buffer. If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param src
- * the buffer with incoming network data
- * @param dst
- * the destination buffer for incoming application data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws java.nio.ReadOnlyBufferException
- * if one of the destination buffers is read-only.
- * @throws IllegalArgumentException
- * if {@code src} or {@code dst} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
- return unwrap(src, new ByteBuffer[] { dst }, 0, 1);
- }
-
- /**
- * Decodes the incoming network data buffer into the application data
- * buffers. If a handshake has not been started yet, it will automatically
- * be started.
- *
- * @param src
- * the buffer with incoming network data
- * @param dsts
- * the array of destination buffers for incoming application
- * data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws java.nio.ReadOnlyBufferException
- * if one of the destination buffers is read-only.
- * @throws IllegalArgumentException
- * if {@code src} or {@code dsts} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts) throws SSLException {
- if (dsts == null) {
- throw new IllegalArgumentException("Byte buffer array dsts is null");
- }
- return unwrap(src, dsts, 0, dsts.length);
- }
-
- /**
- * Encodes the outgoing application data buffers into the network data
- * buffer. If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param srcs
- * the array of source buffers of outgoing application data.
- * @param dst
- * the destination buffer for network data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws java.nio.ReadOnlyBufferException
- * if the destination buffer is readonly.
- * @throws IllegalArgumentException
- * if {@code srcs} or {@code dst} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public SSLEngineResult wrap(ByteBuffer[] srcs, ByteBuffer dst) throws SSLException {
- if (srcs == null) {
- throw new IllegalArgumentException("Byte buffer array srcs is null");
- }
- return wrap(srcs, 0, srcs.length, dst);
- }
-
- /**
- * Encodes the outgoing application data buffer into the network data
- * buffer. If a handshake has not been started yet, it will automatically be
- * started.
- *
- * @param src
- * the source buffers of outgoing application data.
- * @param dst
- * the destination buffer for network data.
- * @return the result object of this operation.
- * @throws SSLException
- * if a problem occurred while processing the data.
- * @throws java.nio.ReadOnlyBufferException
- * if the destination buffer is readonly.
- * @throws IllegalArgumentException
- * if {@code src} or {@code dst} is {@code null}.
- * @throws IllegalStateException
- * if the engine does not have all the needed settings (e.g.
- * client/server mode not set).
- */
- public SSLEngineResult wrap(ByteBuffer src, ByteBuffer dst) throws SSLException {
- return wrap(new ByteBuffer[] { src }, 0, 1, dst);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLEngineResult.java b/x-net/src/main/java/javax/net/ssl/SSLEngineResult.java
deleted file mode 100644
index 8a98831..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLEngineResult.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The result object describing the state of the {@code SSLEngine} produced
- * by the {@code wrap()} and {@code unwrap()} operations.
- */
-public class SSLEngineResult {
-
- /**
- * The {@code enum} describing the state of the current handshake.
- */
- public enum HandshakeStatus {
- /**
- * No handshake in progress.
- */
- NOT_HANDSHAKING,
- /**
- * The handshake is finished.
- */
- FINISHED,
- /**
- * The results of one (or more) delegated tasks are needed to continue
- * the handshake.
- */
- NEED_TASK,
- /**
- * The engine must send data to the remote side to continue the
- * handshake.
- */
- NEED_WRAP,
- /**
- * The engine needs to receive data from the remote side to continue the
- * handshake.
- */
- NEED_UNWRAP
- }
-
- /**
- * The {@code enum} describing the result of the {@code SSLEngine}
- * operation.
- */
- public static enum Status {
- /**
- * The size of the destination buffer is too small to hold the result of
- * the current operation.
- */
- BUFFER_OVERFLOW,
- /**
- * There were not enough bytes available in the source buffer to
- * complete the current operation.
- */
- BUFFER_UNDERFLOW,
- /**
- * The operation closed this side of the communication or was already
- * closed.
- */
- CLOSED,
- /**
- * The operation completed successfully.
- */
- OK
- }
-
- // Store Status object
- private final SSLEngineResult.Status status;
-
- // Store HandshakeStatus object
- private final SSLEngineResult.HandshakeStatus handshakeStatus;
-
- // Store bytesConsumed
- private final int bytesConsumed;
-
- // Store bytesProduced
- private final int bytesProduced;
-
- /**
- * Creates a new {@code SSLEngineResult} instance with the specified state
- * values.
- *
- * @param status
- * the return value of the {@code SSLEngine} operation.
- * @param handshakeStatus
- * the status of the current handshake
- * @param bytesConsumed
- * the number of bytes retrieved from the source buffer(s).
- * @param bytesProduced
- * the number of bytes transferred to the destination buffer(s).
- * @throws IllegalArgumentException
- * if {@code status} or {@code handshakeStatus} is {@code null},
- * or if {@code bytesConsumed} or {@code bytesProduces} are
- * negative.
- */
- public SSLEngineResult(SSLEngineResult.Status status,
- SSLEngineResult.HandshakeStatus handshakeStatus, int bytesConsumed, int bytesProduced) {
- if (status == null) {
- throw new IllegalArgumentException("status is null");
- }
- if (handshakeStatus == null) {
- throw new IllegalArgumentException("handshakeStatus is null");
- }
- if (bytesConsumed < 0) {
- throw new IllegalArgumentException("bytesConsumed is negative");
- }
- if (bytesProduced < 0) {
- throw new IllegalArgumentException("bytesProduced is negative");
- }
- this.status = status;
- this.handshakeStatus = handshakeStatus;
- this.bytesConsumed = bytesConsumed;
- this.bytesProduced = bytesProduced;
- }
-
- /**
- * Returns the return value of the {@code SSLEngine} operation.
- *
- * @return the return value of the {@code SSLEngine} operation.
- */
- public final Status getStatus() {
- return status;
- }
-
- /**
- * Returns the status of the current handshake.
- *
- * @return the status of the current handshake.
- */
- public final HandshakeStatus getHandshakeStatus() {
- return handshakeStatus;
- }
-
- /**
- * Returns the number of bytes retrieved from the source buffer(s).
- *
- * @return the number of bytes retrieved from the source buffer(s).
- */
- public final int bytesConsumed() {
- return bytesConsumed;
- }
-
- /**
- * Returns the number of bytes transferred to the destination buffer(s).
- *
- * @return the number of bytes transferred to the destination buffer(s).
- */
- public final int bytesProduced() {
- return bytesProduced;
- }
-
- @Override
- public String toString() {
- return "SSLEngineReport: Status = " + status + " HandshakeStatus = " + handshakeStatus
- + "\n bytesConsumed = " + bytesConsumed + " bytesProduced = "
- + bytesProduced;
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLException.java b/x-net/src/main/java/javax/net/ssl/SSLException.java
deleted file mode 100644
index 5d716f7..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLException.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-
-/**
- * The base class for all SSL related exceptions.
- */
-public class SSLException extends IOException {
- private static final long serialVersionUID = 4511006460650708967L;
-
- /**
- * Creates a new {@code SSLException} with the specified reason.
- *
- * @param reason
- * the reason for the exception.
- */
- public SSLException(String reason) {
- super(reason);
- }
-
- /**
- * Creates a new {@code SSLException} with the specified message and cause.
- *
- * @param message
- * the detail message for the exception.
- * @param cause
- * the cause.
- */
- public SSLException(String message, Throwable cause) {
- super(message);
- super.initCause(cause);
- }
-
- /**
- * Creates a new {@code SSLException} with the specified cause.
- *
- * @param cause
- * the cause
- */
- public SSLException(Throwable cause) {
- super(cause == null ? null : cause.toString());
- super.initCause(cause);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLHandshakeException.java b/x-net/src/main/java/javax/net/ssl/SSLHandshakeException.java
deleted file mode 100644
index 1c17ae7..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLHandshakeException.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The exception that is thrown when a handshake could not be completed
- * successfully.
- */
-public class SSLHandshakeException extends SSLException {
-
- private static final long serialVersionUID = -5045881315018326890L;
-
- /**
- * Creates a new {@code SSLHandshakeException} with the specified message.
- *
- * @param reason
- * the detail message for the exception.
- */
- public SSLHandshakeException(String reason) {
- super(reason);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLKeyException.java b/x-net/src/main/java/javax/net/ssl/SSLKeyException.java
deleted file mode 100644
index 6d81676..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLKeyException.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The exception that is thrown when an invalid SSL key is encountered.
- */
-public class SSLKeyException extends SSLException {
-
- private static final long serialVersionUID = -8071664081941937874L;
-
- /**
- * Creates a new {@code SSLKeyException} with the specified message.
- *
- * @param reason
- * the detail message for the exception.
- */
- public SSLKeyException(String reason) {
- super(reason);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLPeerUnverifiedException.java b/x-net/src/main/java/javax/net/ssl/SSLPeerUnverifiedException.java
deleted file mode 100644
index bb5bd64..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLPeerUnverifiedException.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The exception that is thrown when the identity of a peer has not beed
- * verified.
- */
-public class SSLPeerUnverifiedException extends SSLException {
-
- private static final long serialVersionUID = -8919512675000600547L;
-
- /**
- * Creates a new {@code SSLPeerUnverifiedException} with the specified
- * message.
- *
- * @param reason
- * the detail message for the exception.
- */
- public SSLPeerUnverifiedException(String reason) {
- super(reason);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLPermission.java b/x-net/src/main/java/javax/net/ssl/SSLPermission.java
deleted file mode 100644
index 5b5c76f..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLPermission.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.BasicPermission;
-
-/**
- * The class representing a network permission.
- * <p>
- * The following permissions are defined, allowing the specified action:
- * <dl>
- * <dt> {@code "setHostnameVerifier"} </dt>
- * <dd> setting a callback object for additional verification of a hostname mismatch.</dd>
- * <dt> {@code "getSSLSessionContext"} </dt>
- * <dd> getting the {@code SSLSessionContext} of an {@code SSLSession}.</dd>
- * </dl>
- */
-public final class SSLPermission extends BasicPermission {
-
- private static final long serialVersionUID = -3456898025505876775L;
-
- /**
- * Creates a new {@code SSLPermission} with the specified name.
- *
- * @param name
- * the permission name.
- */
- public SSLPermission(String name) {
- super(name);
- }
-
- /**
- * Creates a new {@code SSLPermission} with the specified name.
- *
- * @param name
- * the permission name.
- * @param actions
- * is ignored and should be {@code null}.
- */
- public SSLPermission(String name, String actions) {
- super(name, actions);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLProtocolException.java b/x-net/src/main/java/javax/net/ssl/SSLProtocolException.java
deleted file mode 100644
index 50ed74d..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLProtocolException.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The exception that is thrown when an error in the operation of the SSL
- * protocol is encountered.
- */
-public class SSLProtocolException extends SSLException {
-
- private static final long serialVersionUID = 5445067063799134928L;
-
- /**
- * Creates a new {@code SSLProtocolException} with the specified message.
- *
- * @param reason
- * the detail message for the exception.
- */
- public SSLProtocolException(String reason) {
- super(reason);
- }
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLServerSocket.java b/x-net/src/main/java/javax/net/ssl/SSLServerSocket.java
deleted file mode 100644
index 8bd8918..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLServerSocket.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-
-/**
- * The extension of {@code ServerSocket} which provides secure server sockets
- * based on protocols like SSL, TLS, or others.
- */
-public abstract class SSLServerSocket extends ServerSocket {
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP server socket with the default authentication context.
- *
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLServerSocket() throws IOException {
- super();
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP server socket on the specified port with the default
- * authentication context. The connection's default backlog size is 50
- * connections.
- * @param port
- * the port to listen on.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLServerSocket(int port) throws IOException {
- super(port);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP server socket on the specified port using the specified
- * backlog and the default authentication context.
- *
- * @param port
- * the port to listen on.
- * @param backlog
- * the number of pending connections to queue.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLServerSocket(int port, int backlog) throws IOException {
- super(port, backlog);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP server socket on the specified port, using the specified
- * backlog, listening on the specified interface, and using the default
- * authentication context.
- *
- * @param port
- * the port the listen on.
- * @param backlog
- * the number of pending connections to queue.
- * @param address
- * the address of the interface to accept connections on.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLServerSocket(int port, int backlog, InetAddress address) throws IOException {
- super(port, backlog, address);
- }
-
- /**
- * Returns the names of the enabled cipher suites to be used for new
- * connections.
- *
- * @return the names of the enabled cipher suites to be used for new
- * connections.
- */
- public abstract String[] getEnabledCipherSuites();
-
- /**
- * Sets the names of the cipher suites to be enabled for new connections.
- * Only cipher suites returned by {@link #getSupportedCipherSuites()} are
- * allowed.
- *
- * @param suites
- * the names of the to be enabled cipher suites.
- * @throws IllegalArgumentException
- * if one of the cipher suite names is not supported.
- */
- public abstract void setEnabledCipherSuites(String[] suites);
-
- /**
- * Returns the names of the supported cipher suites.
- *
- * @return the names of the supported cipher suites.
- */
- public abstract String[] getSupportedCipherSuites();
-
- /**
- * Returns the names of the supported protocols.
- *
- * @return the names of the supported protocols.
- */
- public abstract String[] getSupportedProtocols();
-
- /**
- * Returns the names of the enabled protocols to be used for new
- * connections.
- *
- * @return the names of the enabled protocols to be used for new
- * connections.
- */
- public abstract String[] getEnabledProtocols();
-
- /**
- * Sets the names of the protocols to be enabled for new connections. Only
- * protocols returned by {@link #getSupportedProtocols()} are allowed.
- *
- * @param protocols
- * the names of the to be enabled protocols.
- * @throws IllegalArgumentException
- * if one of the protocols is not supported.
- */
- public abstract void setEnabledProtocols(String[] protocols);
-
- /**
- * Sets whether server-mode connections will be configured to require client
- * authentication. The client authentication is one of the following:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setWantClientAuth(boolean)}.
- *
- * @param need
- * {@code true} if client authentication is required,
- * {@code false} if no authentication is needed.
- */
- public abstract void setNeedClientAuth(boolean need);
-
- /**
- * Returns whether server-mode connections will be configured to require
- * client authentication.
- *
- * @return {@code true} if client authentication is required, {@code false}
- * if no client authentication is needed.
- */
- public abstract boolean getNeedClientAuth();
-
- /**
- * Sets whether server-mode connections will be configured to request client
- * authentication. The client authentication is one of the following:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setNeedClientAuth(boolean)}.
- *
- * @param want
- * {@code true} if client authentication should be requested,
- * {@code false} if no authentication is needed.
- */
- public abstract void setWantClientAuth(boolean want);
-
- /**
- * Returns whether server-mode connections will be configured to request
- * client authentication.
- *
- * @return {@code true} is client authentication will be requested,
- * {@code false} if no client authentication is needed.
- */
- public abstract boolean getWantClientAuth();
-
- /**
- * Sets whether new connections should act in client mode when handshaking.
- *
- * @param mode
- * {@code true} if new connections should act in client mode,
- * {@code false} if not.
- */
- public abstract void setUseClientMode(boolean mode);
-
- /**
- * Returns whether new connection will act in client mode when handshaking.
- *
- * @return {@code true} if new connections will act in client mode when
- * handshaking, {@code false} if not.
- */
- public abstract boolean getUseClientMode();
-
- /**
- * Sets whether new SSL sessions may be established for new connections.
- *
- * @param flag
- * {@code true} if new SSL sessions may be established,
- * {@code false} if existing SSL sessions must be reused.
- */
- public abstract void setEnableSessionCreation(boolean flag);
-
- /**
- * Returns whether new SSL sessions may be established for new connections.
- *
- * @return {@code true} if new SSL sessions may be established,
- * {@code false} if existing SSL sessions must be reused.
- */
- public abstract boolean getEnableSessionCreation();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLServerSocketFactory.java b/x-net/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
deleted file mode 100644
index ccb2c5d..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLServerSocketFactory.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.security.Security;
-
-import javax.net.ServerSocketFactory;
-
-/**
- * The factory for SSL server sockets.
- */
-public abstract class SSLServerSocketFactory extends ServerSocketFactory {
- // TODO EXPORT CONTROL
-
- // The default SSL socket factory
- private static ServerSocketFactory defaultServerSocketFactory;
-
- private static String defaultName;
-
- /**
- * Returns the default {@code SSLServerSocketFactory} instance. The default
- * implementation is defined by the security property
- * "ssl.ServerSocketFactory.provider".
- *
- * @return the default {@code SSLServerSocketFactory} instance.
- */
- public static synchronized ServerSocketFactory getDefault() {
- if (defaultServerSocketFactory != null) {
- return defaultServerSocketFactory;
- }
- if (defaultName == null) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- defaultName = Security.getProperty("ssl.ServerSocketFactory.provider");
- if (defaultName != null) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- try {
- final Class<?> ssfc = Class.forName(defaultName, true, cl);
- defaultServerSocketFactory = (ServerSocketFactory) ssfc.newInstance();
- } catch (Exception e) {
- }
- }
- return null;
- }
- });
- }
- if (defaultServerSocketFactory == null) {
- // Try to find in providers
- SSLContext context = DefaultSSLContext.getContext();
- if (context != null) {
- defaultServerSocketFactory = context.getServerSocketFactory();
- }
- }
- if (defaultServerSocketFactory == null) {
- // Use internal dummy implementation
- defaultServerSocketFactory = new DefaultSSLServerSocketFactory(
- "No ServerSocketFactory installed");
- }
- return defaultServerSocketFactory;
- }
-
- /**
- * Creates a new {@code SSLServerSocketFactory} instance.
- */
- protected SSLServerSocketFactory() {
- super();
- }
-
- /**
- * Returns the names of the cipher suites that are enabled by default.
- *
- * @return the names of the cipher suites that are enabled by default
- */
- public abstract String[] getDefaultCipherSuites();
-
- /**
- * Returns the list of supported cipher suites that could be enabled for an
- * SSL connection created by this factory.
- *
- * @return the list of supported cipher suites
- */
- public abstract String[] getSupportedCipherSuites();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSession.java b/x-net/src/main/java/javax/net/ssl/SSLSession.java
deleted file mode 100644
index 14a312a..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSession.java
+++ /dev/null
@@ -1,231 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.Principal;
-import java.security.cert.Certificate;
-import javax.security.cert.X509Certificate;
-
-/**
- * The interface representing an SSL session.
- */
-public interface SSLSession {
-
- /**
- * Returns the maximum size that an application buffer can be for this
- * session.
- *
- * @return the maximum application buffer size.
- */
- public int getApplicationBufferSize();
-
- /**
- * Returns the name of the cipher suite used in this session.
- *
- * @return the name of the cipher suite used in this session.
- */
- public String getCipherSuite();
-
- /**
- * Returns the time this session was created, in milliseconds since midnight
- * January 1st 1970 UTC.
- *
- * @return the time the session was created.
- */
- public long getCreationTime();
-
- /**
- * Returns this sessions identifier.
- *
- * @return this sessions identifier.
- */
- public byte[] getId();
-
- /**
- * Returns the time this session was last accessed, in milliseconds since
- * midnight January 1st 1970 UTC.
- *
- * @return the time this session was last accessed.
- */
- public long getLastAccessedTime();
-
- /**
- * Returns the list of certificates that were used to identify the local
- * side to the peer during the handshake.
- *
- * @return the list of certificates, ordered from local certificate to
- * CA's certificates.
- */
- public Certificate[] getLocalCertificates();
-
- /**
- * Returns the principal used to identify the local side to the peer during
- * the handshake.
- *
- * @return the principal used to identify the local side.
- */
- public Principal getLocalPrincipal();
-
- /**
- * Returns the maximum size that a network buffer can be for this session.
- *
- * @return the maximum network buffer size.
- */
- public int getPacketBufferSize();
-
- /**
- * Returns the list of certificates the peer used to identify itself during
- * the handshake.
- * <p>
- * Note: this method exists for compatility reasons, use
- * {@link #getPeerCertificates()} instead.
- *
- * @return the list of certificates, ordered from the identity certificate to
- * the CA's certificates
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer is not verified.
- */
- public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException;
-
- /**
- * Returns the list of certificates the peer used to identify itself during
- * the handshake.
- *
- * @return the list of certificates, ordered from the identity certificate to
- * the CA's certificates.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer is not verified.
- */
- public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException;
-
- /**
- * Returns the host name of the peer of this session. The host name is not
- * authenticated.
- *
- * @return the host name of the peer of this session, or {@code null} if no
- * host name is available.
- */
- public String getPeerHost();
-
- /**
- * Returns the port number of the peer of this session. The port number is
- * not authenticated.
- *
- * @return the port number of the peer, of {@code -1} is no port number is
- * available.
- */
- public int getPeerPort();
-
- /**
- * Returns the principal identifying the peer during the handshake.
- *
- * @return the principal identifying the peer.
- * @throws SSLPeerUnverifiedException
- * if the identity of the peer has not been verified.
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException;
-
- /**
- * Returns the protocol name that is used for all connections in this
- * session.
- *
- * @return the protocol name that is used for all connections in this
- * session.
- */
- public String getProtocol();
-
- /**
- * Returns the context of this session. If a context is available and a
- * security manager is installed, the
- * {@code SSLPermission("getSSLSessionContext"} is checked with the security
- * manager.
- *
- * @return the context of this session or {@code null} if no context is
- * available.
- */
- public SSLSessionContext getSessionContext();
-
- /**
- * Returns the object bound to the specified name in this session's
- * application layer data.
- *
- * @param name
- * the name of the bound value.
- * @return the value bound to the specified name, or {@code null} if the
- * specified name does not exist or is not accessible in the current
- * access control context.
- * @throws IllegalArgumentException
- * if {@code name} is {@code null}.
- */
- public Object getValue(String name);
-
- /**
- * Returns the list of the object names bound to this session's application
- * layer data..
- * <p>
- * Depending on the current access control context, the list of object names
- * may be different.
- *
- * @return the list of the object names bound to this session's application
- * layer data.
- */
- public String[] getValueNames();
-
- /**
- * Invalidates this session.
- * <p>
- * No new connections can be created, but any existing connection remains
- * valid until it is closed.
- */
- public void invalidate();
-
- /**
- * Returns whether this session is valid.
- *
- * @return {@code true} if this session is valid, otherwise {@code false}.
- */
- public boolean isValid();
-
- /**
- * Binds the specified object under the specified name in this session's
- * application layer data.
- * <p>
- * For bindings (new or existing) implementing the
- * {@code SSLSessionBindingListener} interface the object will be notified.
- *
- * @param name
- * the name to bind the object to.
- * @param value
- * the object to bind.
- * @throws IllegalArgumentException
- * if either {@code name} or {@code value} is {@code null}.
- */
- public void putValue(String name, Object value);
-
- /**
- * Removes the binding for the specified name in this session's application
- * layer data. If the existing binding implements the
- * {@code SSLSessionBindingListener} interface the object will be notified.
- *
- * @param name
- * the binding to remove.
- * @throws IllegalArgumentException
- * if {@code name} is {@code null}.
- */
- public void removeValue(String name);
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSessionBindingEvent.java b/x-net/src/main/java/javax/net/ssl/SSLSessionBindingEvent.java
deleted file mode 100644
index 19ae835..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSessionBindingEvent.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.Serializable;
-import java.util.EventObject;
-
-/**
- * The event sent to an {@code SSLSessionBindingListener} when the listener
- * object is bound ({@link SSLSession#putValue(String, Object)}) or unbound
- * ({@link SSLSession#removeValue(String)}) to an {@code SSLSession}.
- */
-public class SSLSessionBindingEvent extends EventObject implements Serializable {
-
- /**
- * The 5.0 spec. doesn't declare this serialVersionUID field In order to be compatible it is
- * explicitly declared here
- */
- private static final long serialVersionUID = 3989172637106345L;
-
- /**
- * @serial include
- */
- private final String name;
-
- /**
- * Creates a new {@code SSLSessionBindingEvent} for the specified session
- * indicating a binding event for the specified name.
- *
- * @param session
- * the session for which the event occurs.
- * @param name
- * the name of the object being (un)bound.
- */
- public SSLSessionBindingEvent(SSLSession session, String name) {
- super(session);
- this.name = name;
- }
-
- /**
- * Returns the name of the binding being added or removed.
- *
- * @return the name of the binding.
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns the session to which the binding is added or from which it is
- * removed.
- *
- * @return the session to which the binding is added or from which it is
- * removed.
- */
- public SSLSession getSession() {
- return (SSLSession) this.source;
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSessionBindingListener.java b/x-net/src/main/java/javax/net/ssl/SSLSessionBindingListener.java
deleted file mode 100644
index 43ad745..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSessionBindingListener.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.util.EventListener;
-
-/**
- * The interface to be implemented by any object that requires notification when
- * data objects are bound to (or unbound from) an {@code SSLSession}.
- */
-public interface SSLSessionBindingListener extends EventListener {
-
- /**
- * Notifies this listener when a value is bound to an {@code SSLSession}.
- *
- * @param event
- * the event data.
- */
- public void valueBound(SSLSessionBindingEvent event);
-
- /**
- * Notifies this listener when a value is unbound from an {@code SSLSession}.
- *
- * @param event
- * the event data.
- */
- public void valueUnbound(SSLSessionBindingEvent event);
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSessionContext.java b/x-net/src/main/java/javax/net/ssl/SSLSessionContext.java
deleted file mode 100644
index 154376e..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSessionContext.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.util.Enumeration;
-
-/**
- * A collection of {@code SSLSession}s.
- */
-public interface SSLSessionContext {
- /**
- * Returns an iterable of all session identifiers in this session context.
- *
- * @return an iterable of all session identifiers in this session context.
- */
- @SuppressWarnings("unchecked")
- public Enumeration getIds();
-
- /**
- * Returns the session for the specified session identifier.
- *
- * @param sessionId
- * the session identifier of the session to look up.
- * @return the session for the specified session identifier, or {@code null}
- * if the specified session identifier does not refer to a session
- * in this context.
- */
- public SSLSession getSession(byte[] sessionId);
-
- /**
- * Returns the size of the session cache for this session context.
- *
- * @return the size of the session cache for this session context, or
- * {@code zero} if unlimited.
- */
- public int getSessionCacheSize();
-
- /**
- * Returns the timeout for sessions in this session context. Sessions
- * exceeding the timeout are invalidated.
- *
- * @return the timeout in seconds, or {@code zero} if unlimited.
- */
- public int getSessionTimeout();
-
- /**
- * Sets the size of the session cache for this session context.
- *
- * @param size
- * the size of the session cache, or {@code zero} for unlimited
- * cache size.
- * @throws IllegalArgumentException
- * if {@code size} is negative.
- */
- public void setSessionCacheSize(int size) throws IllegalArgumentException;
-
- /**
- * Sets the timeout for sessions in this context. Sessions exceeding the
- * timeout are invalidated.
- *
- * @param seconds
- * the timeout in seconds, or {@code zero} if unlimited.
- * @throws IllegalArgumentException
- * if {@code seconds} is negative.
- */
- public void setSessionTimeout(int seconds) throws IllegalArgumentException;
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSocket.java b/x-net/src/main/java/javax/net/ssl/SSLSocket.java
deleted file mode 100644
index 4a70843..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSocket.java
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-
-/**
- * The extension of {@code Socket} providing secure protocols like SSL (Secure
- * Socket Layer") or TLS (Transport Layer Security).
- */
-public abstract class SSLSocket extends Socket {
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket.
- */
- protected SSLSocket() {
- super();
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket connection to the specified host at the specified
- * port.
- *
- * @param host
- * the host name to connect to.
- * @param port
- * the port number to connect to.
- * @throws IOException
- * if creating the socket fails.
- * @throws UnknownHostException
- * if the specified host is not known.
- */
- protected SSLSocket(String host, int port) throws IOException, UnknownHostException {
- super(host, port);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket connection to the specified address at the specified
- * port.
- *
- * @param address
- * the address to connect to.
- * @param port
- * the port number to connect to.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLSocket(InetAddress address, int port) throws IOException {
- super(address, port);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket connection to the specified host at the specified
- * port with the client side bound to the specified address and port.
- *
- * @param host
- * the host name to connect to.
- * @param port
- * the port number to connect to.
- * @param clientAddress
- * the client address to bind to
- * @param clientPort
- * the client port number to bind to.
- * @throws IOException
- * if creating the socket fails.
- * @throws UnknownHostException
- * if the specified host is not known.
- */
- protected SSLSocket(String host, int port, InetAddress clientAddress, int clientPort)
- throws IOException, UnknownHostException {
- super(host, port, clientAddress, clientPort);
- }
-
- /**
- * Only to be used by subclasses.
- * <p>
- * Creates a TCP socket connection to the specified address at the specified
- * port with the client side bound to the specified address and port.
- *
- * @param address
- * the address to connect to.
- * @param port
- * the port number to connect to.
- * @param clientAddress
- * the client address to bind to.
- * @param clientPort
- * the client port number to bind to.
- * @throws IOException
- * if creating the socket fails.
- */
- protected SSLSocket(InetAddress address, int port, InetAddress clientAddress, int clientPort)
- throws IOException {
- super(address, port, clientAddress, clientPort);
- }
-
- /**
- * Returns the names of the supported cipher suites.
- *
- * @return the names of the supported cipher suites.
- */
- public abstract String[] getSupportedCipherSuites();
-
- /**
- * Returns the names of the enabled cipher suites.
- *
- * @return the names of the enabled cipher suites.
- */
- public abstract String[] getEnabledCipherSuites();
-
- /**
- * Sets the names of the cipher suites to be enabled.
- * Only cipher suites returned by {@link #getSupportedCipherSuites()} are
- * allowed.
- *
- * @param suites
- * the names of the to be enabled cipher suites.
- * @throws IllegalArgumentException
- * if one of the cipher suite names is not supported.
- */
- public abstract void setEnabledCipherSuites(String[] suites);
-
- /**
- * Returns the names of the supported protocols.
- *
- * @return the names of the supported protocols.
- */
- public abstract String[] getSupportedProtocols();
-
- /**
- * Returns the names of the enabled protocols.
- *
- * @return the names of the enabled protocols.
- */
- public abstract String[] getEnabledProtocols();
-
- /**
- * Sets the names of the protocols to be enabled. Only
- * protocols returned by {@link #getSupportedProtocols()} are allowed.
- *
- * @param protocols
- * the names of the to be enabled protocols.
- * @throws IllegalArgumentException
- * if one of the protocols is not supported.
- */
- public abstract void setEnabledProtocols(String[] protocols);
-
- /**
- * Returns the {@code SSLSession} for this connection. If necessary, a
- * handshake will be initiated, in which case this method will block until the handshake
- * has been established. If the handshake fails, an invalid session object
- * will be returned.
- *
- * @return the session object.
- */
- public abstract SSLSession getSession();
-
- /**
- * Registers the specified listener to receive notification on completion of a
- * handshake on this connection.
- *
- * @param listener
- * the listener to register.
- * @throws IllegalArgumentException
- * if {@code listener} is {@code null}.
- */
- public abstract void addHandshakeCompletedListener(HandshakeCompletedListener listener);
-
- /**
- * Removes the specified handshake completion listener.
- *
- * @param listener
- * the listener to remove.
- * @throws IllegalArgumentException
- * if the specified listener is not registered or {@code null}.
- */
- public abstract void removeHandshakeCompletedListener(HandshakeCompletedListener listener);
-
- /**
- * Starts a new SSL handshake on this connection.
- *
- * @throws IOException
- * if an error occurs.
- */
- public abstract void startHandshake() throws IOException;
-
- /**
- * Sets whether this connection should act in client mode when handshaking.
- *
- * @param mode
- * {@code true} if this connection should act in client mode,
- * {@code false} if not.
- */
- public abstract void setUseClientMode(boolean mode);
-
- /**
- * Returns whether this connection will act in client mode when handshaking.
- *
- * @return {@code true} if this connections will act in client mode when
- * handshaking, {@code false} if not.
- */
- public abstract boolean getUseClientMode();
-
- /**
- * Sets whether this connection should require client authentication. This
- * is only useful for sockets in server mode. The client authentication is
- * one of the following:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setWantClientAuth(boolean)}.
- *
- * @param need
- * {@code true} if client authentication is required,
- * {@code false} if no authentication is needed.
- */
- public abstract void setNeedClientAuth(boolean need);
-
- /**
- * Returns whether this connection requires client authentication.
- * This is only useful for sockets in server mode.
- *
- * @return {@code true} if client authentication is required, {@code false}
- * if no client authentication is needed.
- */
- public abstract boolean getNeedClientAuth();
-
- /**
- * Sets whether this connections should request client authentication. This
- * is only useful for sockets in server mode. The client authentication is
- * one of:
- * <ul>
- * <li>authentication required</li>
- * <li>authentication requested</li>
- * <li>no authentication needed</li>
- * </ul>
- * This method overrides the setting of {@link #setNeedClientAuth(boolean)}.
- *
- * @param want
- * {@code true} if client authentication should be requested,
- * {@code false} if not authentication is needed.
- */
- public abstract void setWantClientAuth(boolean want);
-
- /**
- * Returns whether this connections will request client authentication.
- *
- * @return {@code true} is client authentication will be requested,
- * {@code false} if no client authentication is needed.
- */
- public abstract boolean getWantClientAuth();
-
- /**
- * Sets whether new SSL sessions may be created by this socket or if
- * existing sessions must be reused.
- *
- * @param flag
- * {@code true} if new sessions may be created, otherwise
- * {@code false}.
- */
- public abstract void setEnableSessionCreation(boolean flag);
-
- /**
- * Returns whether new SSL sessions may be created by this socket or if
- * existing sessions must be reused.
- *
- * @return {@code true} if new sessions may be created, otherwise
- * {@code false}.
- */
- public abstract boolean getEnableSessionCreation();
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/SSLSocketFactory.java b/x-net/src/main/java/javax/net/ssl/SSLSocketFactory.java
deleted file mode 100644
index b75c218..0000000
--- a/x-net/src/main/java/javax/net/ssl/SSLSocketFactory.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.io.IOException;
-import java.net.Socket;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.security.Security;
-// BEGIN android-added
-import java.util.logging.Level;
-import java.util.logging.Logger;
-// END android-added
-
-import javax.net.SocketFactory;
-
-/**
- * The abstract factory implementation to create {@code SSLSocket}s.
- */
-public abstract class SSLSocketFactory extends SocketFactory {
- // FIXME EXPORT CONTROL
-
- // The default SSL socket factory
- private static SocketFactory defaultSocketFactory;
-
- private static String defaultName;
-
- /**
- * Returns the default {@code SSLSocketFactory} instance. The default is
- * defined by the security property {@code 'ssl.SocketFactory.provider'}.
- *
- * @return the default ssl socket factory instance.
- */
- public static synchronized SocketFactory getDefault() {
- if (defaultSocketFactory != null) {
- // BEGIN android-added
- // log("SSLSocketFactory", "Using factory " + defaultSocketFactory, null);
- // END android-added
- return defaultSocketFactory;
- }
- if (defaultName == null) {
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- defaultName = Security.getProperty("ssl.SocketFactory.provider");
- if (defaultName != null) {
- ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null) {
- cl = ClassLoader.getSystemClassLoader();
- }
- try {
- final Class<?> sfc = Class.forName(defaultName, true, cl);
- defaultSocketFactory = (SocketFactory) sfc.newInstance();
- } catch (Exception e) {
- // BEGIN android-added
- log("SSLSocketFactory", "Problem creating " + defaultName, e);
- // END android-added
- }
- }
- return null;
- }
- });
- }
-
- if (defaultSocketFactory == null) {
- // Try to find in providers
- SSLContext context = DefaultSSLContext.getContext();
- if (context != null) {
- defaultSocketFactory = context.getSocketFactory();
- }
- }
- if (defaultSocketFactory == null) {
- // Use internal implementation
- defaultSocketFactory = new DefaultSSLSocketFactory("No SSLSocketFactory installed");
- }
- // BEGIN android-added
- // log("SSLSocketFactory", "Using factory " + defaultSocketFactory, null);
- // END android-added
- return defaultSocketFactory;
- }
-
- // BEGIN android-added
- @SuppressWarnings("unchecked")
- private static void log(String tag, String msg, Throwable throwable) {
- Logger.getLogger(tag).log(Level.INFO, msg, throwable);
- }
- // END android-added
-
- /**
- * Creates a new {@code SSLSocketFactory}.
- */
- public SSLSocketFactory() {
- super();
- }
-
- /**
- * Returns the names of the cipher suites that are enabled by default.
- *
- * @return the names of the cipher suites that are enabled by default.
- */
- public abstract String[] getDefaultCipherSuites();
-
- /**
- * Returns the names of the cipher suites that are supported and could be
- * enabled for an SSL connection.
- *
- * @return the names of the cipher suites that are supported.
- */
- public abstract String[] getSupportedCipherSuites();
-
- /**
- * Creates an {@code SSLSocket} over the specified socket that is connected
- * to the specified host at the specified port.
- *
- * @param s
- * the socket.
- * @param host
- * the host.
- * @param port
- * the port number.
- * @param autoClose
- * {@code true} if socket {@code s} should be closed when the
- * created socket is closed, {@code false} if the socket
- * {@code s} should be left open.
- * @return the creates ssl socket.
- * @throws IOException
- * if creating the socket fails.
- * @throws java.net.UnknownHostException
- * if the host is unknown.
- */
- public abstract Socket createSocket(Socket s, String host, int port, boolean autoClose)
- throws IOException;
-}
diff --git a/x-net/src/main/java/javax/net/ssl/TrustManager.java b/x-net/src/main/java/javax/net/ssl/TrustManager.java
deleted file mode 100644
index 9bdb16b..0000000
--- a/x-net/src/main/java/javax/net/ssl/TrustManager.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-/**
- * The marker interface for JSSE trust managers. The purpose is to group trust
- * managers. The responsibility a trust manager is to handle the trust data used to
- * make trust decisions for deciding whether credentials of a peer should be
- * accepted,
- * @see TrustManagerFactory
- */
-public interface TrustManager {
-}
diff --git a/x-net/src/main/java/javax/net/ssl/TrustManagerFactory.java b/x-net/src/main/java/javax/net/ssl/TrustManagerFactory.java
deleted file mode 100644
index 6d9e4c9..0000000
--- a/x-net/src/main/java/javax/net/ssl/TrustManagerFactory.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
-import java.security.PrivilegedAction;
-import java.security.Provider;
-import java.security.Security;
-
-import org.apache.harmony.security.fortress.Engine;
-
-/**
- * The factory for {@code TrustManager}s based on {@code KeyStore} or provider
- * specific implementation.
- */
-public class TrustManagerFactory {
- // Store TrustManager service name
- private static final String SERVICE = "TrustManagerFactory";
-
- // Used to access common engine functionality
- private static Engine engine = new Engine(SERVICE);
-
- // Store default property name
- private static final String PROPERTYNAME = "ssl.TrustManagerFactory.algorithm";
-
- /**
- * Returns the default algorithm name for the {@code TrustManagerFactory}. The
- * default algorithm name is specified by the security property
- * {@code 'ssl.TrustManagerFactory.algorithm'}.
- *
- * @return the default algorithm name.
- */
- public static final String getDefaultAlgorithm() {
- return AccessController.doPrivileged(new PrivilegedAction<String>() {
- public String run() {
- return Security.getProperty(PROPERTYNAME);
- }
- });
- }
-
- /**
- * Creates a new {@code TrustManagerFactory} instance for the specified
- * trust management algorithm.
- *
- * @param algorithm
- * the name of the requested trust management algorithm.
- * @return a trust manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if no installed provider can provide the requested algorithm.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final TrustManagerFactory getInstance(String algorithm)
- throws NoSuchAlgorithmException {
- if (algorithm == null) {
- throw new NullPointerException("algorithm is null");
- }
- synchronized (engine) {
- engine.getInstance(algorithm, null);
- return new TrustManagerFactory((TrustManagerFactorySpi) engine.spi, engine.provider,
- algorithm);
- }
- }
-
- /**
- * Creates a new {@code TrustManagerFactory} instance for the specified
- * trust management algorithm from the specified provider.
- *
- * @param algorithm
- * the name of the requested trust management algorithm name.
- * @param provider
- * the name of the provider that provides the requested
- * algorithm.
- * @return a trust manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * algorithm.
- * @throws NoSuchProviderException
- * if the specified provider does not exist.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final TrustManagerFactory getInstance(String algorithm, String provider)
- throws NoSuchAlgorithmException, NoSuchProviderException {
- if ((provider == null) || (provider.length() == 0)) {
- throw new IllegalArgumentException("Provider is null oe empty");
- }
- Provider impProvider = Security.getProvider(provider);
- if (impProvider == null) {
- throw new NoSuchProviderException(provider);
- }
- return getInstance(algorithm, impProvider);
- }
-
- /**
- * Creates a new {@code TrustManagerFactory} instance for the specified
- * trust management algorithm from the specified provider.
- *
- * @param algorithm
- * the name of the requested key management algorithm name.
- * @param provider
- * the provider that provides the requested algorithm.
- * @return a key manager factory for the requested algorithm.
- * @throws NoSuchAlgorithmException
- * if the specified provider cannot provide the requested
- * algorithm.
- * @throws NullPointerException
- * if {@code algorithm} is {@code null} (instead of
- * NoSuchAlgorithmException as in 1.4 release)
- */
- public static final TrustManagerFactory getInstance(String algorithm, Provider provider)
- throws NoSuchAlgorithmException {
- if (provider == null) {
- throw new IllegalArgumentException("Provider is null");
- }
- if (algorithm == null) {
- throw new NullPointerException("algorithm is null");
- }
- synchronized (engine) {
- engine.getInstance(algorithm, provider, null);
- return new TrustManagerFactory((TrustManagerFactorySpi) engine.spi, provider, algorithm);
- }
- }
-
- // Store used provider
- private final Provider provider;
-
- // Store used TrustManagerFactorySpi implementation
- private final TrustManagerFactorySpi spiImpl;
-
- // Store used algorithm
- private final String algorithm;
-
- /**
- * Creates a new {@code TrustManagerFactory} instance.
- *
- * @param factorySpi
- * the implementation delegate.
- * @param provider
- * the provider
- * @param algorithm
- * the algorithm name.
- */
- protected TrustManagerFactory(TrustManagerFactorySpi factorySpi, Provider provider,
- String algorithm) {
- this.provider = provider;
- this.algorithm = algorithm;
- this.spiImpl = factorySpi;
- }
-
- /**
- * Returns the name of this {@code TrustManagerFactory} algorithm
- * implementation.
- *
- * @return the name of this {@code TrustManagerFactory} algorithm
- * implementation.
- */
- public final String getAlgorithm() {
- return algorithm;
- }
-
- /**
- * Returns the provider for this {@code TrustManagerFactory} instance.
- *
- * @return the provider for this {@code TrustManagerFactory} instance.
- */
- public final Provider getProvider() {
- return provider;
- }
-
- /**
- * Initializes this factory instance with the specified keystore as source
- * of certificate authorities and trust material.
- *
- * @param ks
- * the keystore or {@code null}.
- * @throws KeyStoreException
- * if the initialization fails.
- */
- public final void init(KeyStore ks) throws KeyStoreException {
- spiImpl.engineInit(ks);
- }
-
- /**
- * Initializes this factory instance with the specified provider-specific
- * parameters for a source of trust material.
- *
- * @param spec
- * the provider-specific parameters.
- * @throws InvalidAlgorithmParameterException
- * if the initialization fails.
- */
- public final void init(ManagerFactoryParameters spec) throws InvalidAlgorithmParameterException {
- spiImpl.engineInit(spec);
- }
-
- /**
- * Returns the list of {@code TrustManager}s with one entry for each type
- * of trust material.
- *
- * @return the list of {@code TrustManager}s
- */
- public final TrustManager[] getTrustManagers() {
- return spiImpl.engineGetTrustManagers();
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/TrustManagerFactorySpi.java b/x-net/src/main/java/javax/net/ssl/TrustManagerFactorySpi.java
deleted file mode 100644
index 1b04c5b..0000000
--- a/x-net/src/main/java/javax/net/ssl/TrustManagerFactorySpi.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-
-/**
- * The <i>Service Provider Interface</i> (SPI) for the
- * {@code TrustManagerFactory} class.
- */
-public abstract class TrustManagerFactorySpi {
-
- /**
- * Creates a new {@code TrustManagerFactorySpi} instance.
- */
- public TrustManagerFactorySpi() {
- super();
- }
-
- /**
- * Initializes this factory instance with the specified keystore as source
- * of certificate authorities and trust material.
- *
- * @param ks
- * the keystore or {@code null}.
- * @throws KeyStoreException
- * if the initialization fails.
- */
- protected abstract void engineInit(KeyStore ks) throws KeyStoreException;
-
- /**
- * Initializes this factory instance with the specified provider-specific
- * parameters for a source of trust material.
- *
- * @param spec
- * the provider-specific parameters.
- * @throws InvalidAlgorithmParameterException
- * if the initialization fails.
- */
- protected abstract void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException;
-
- /**
- * Returns the list of {@code TrustManager}s with one entry for each type
- * of trust material.
- *
- * @return the list of {@code TrustManager}s
- */
- protected abstract TrustManager[] engineGetTrustManagers();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/X509ExtendedKeyManager.java b/x-net/src/main/java/javax/net/ssl/X509ExtendedKeyManager.java
deleted file mode 100644
index 3298d8e..0000000
--- a/x-net/src/main/java/javax/net/ssl/X509ExtendedKeyManager.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.Principal;
-
-/**
- * The abstract extension for the {@code X509KeyManager} interface.
- */
-public abstract class X509ExtendedKeyManager implements X509KeyManager {
-
- /**
- * To be used by subclasses only.
- * <p>
- * Creates a new {@code X509ExtendedKeyManager} instance.
- */
- protected X509ExtendedKeyManager() {
- super();
- }
-
- /**
- * Chooses an alias for the client side of an SSL connection to authenticate
- * it with the specified public key type and certificate issuers.
- *
- * @param keyType
- * the list of public key algorithm names.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @param engine
- * the {@code SSLEngine} for the connection, or {@code null} if
- * no engine is predefined.
- * @return the alias name of a matching key or {@code null} if there are no
- * matches.
- */
- public String chooseEngineClientAlias(String[] keyType,
- Principal[] issuers, SSLEngine engine) {
- return null;
- }
-
- /**
- * Chooses an alias for the server side of an SSL connection to authenticate
- * it with the specified public key type and certificate issuers.
- *
- * @param keyType
- * the list of public key algorithm names.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @param engine
- * the {@code SSLEngine} for the connection, or {@code null} if
- * no engine is predefined.
- * @return the alias name of a matching key or {@code null} if there are no
- * matches.
- */
- public String chooseEngineServerAlias(String keyType, Principal[] issuers,
- SSLEngine engine) {
- return null;
- }
-
-}
diff --git a/x-net/src/main/java/javax/net/ssl/X509KeyManager.java b/x-net/src/main/java/javax/net/ssl/X509KeyManager.java
deleted file mode 100644
index aebc427..0000000
--- a/x-net/src/main/java/javax/net/ssl/X509KeyManager.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.net.Socket;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-
-/**
- * A Key Manager for X509 certificate-based key pairs.
- */
-public interface X509KeyManager extends KeyManager {
-
- /**
- * Chooses an alias for the client side of an SSL connection to authenticate
- * it with the specified public key type and certificate issuers.
- *
- * @param keyType
- * the list of public key algorithm names.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @param socket
- * the socket for the connection, or {@code null} if
- * the alias selected does not depend on a specific socket.
- * @return the alias name of a matching key or {@code null} if there are no
- * matches.
- */
- public String chooseClientAlias(String[] keyType, Principal[] issuers,
- Socket socket);
-
- /**
- * Chooses an alias for the server side of an SSL connection to authenticate
- * it with the specified public key type and certificate issuers.
- *
- * @param keyType
- * the list of public key algorithm type names.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @param socket
- * the socket for the connection, or {@code null} if
- * the alias selected does not depend on a specific socket.
- * @return the alias name of a matching key or {@code null} if there are no
- * matches.
- */
- public String chooseServerAlias(String keyType, Principal[] issuers,
- Socket socket);
-
- /**
- * Returns the certificate chain for the specified alias.
- *
- * @param alias
- * the alias to get the certificate chain for.
- * @return the certificate chain for the specified alias, or {@code null} if
- * the alias cannot be found.
- */
- public X509Certificate[] getCertificateChain(String alias);
-
- /**
- * Returns the client aliases for the specified public key type and list of
- * certificate issuers.
- *
- * @param keyType
- * the public key algorithm type name.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @return the client aliases for the specified public key type, or
- * {@code null} if there are no matching aliases.
- */
- public String[] getClientAliases(String keyType, Principal[] issuers);
-
- /**
- * Returns the server aliases for the specified public key type and list of
- * certificate issuers.
- *
- * @param keyType
- * the public key algorithm type name.
- * @param issuers
- * the list of certificate issuers, or {@code null} if any issuer
- * will do.
- * @return the client aliases for the specified public key type, or
- * {@code null} if there are no matching aliases.
- */
- public String[] getServerAliases(String keyType, Principal[] issuers);
-
- /**
- * Returns the private key for the specified alias.
- *
- * @param alias
- * the alias to get the private key for.
- * @return the private key for the specified alias, or {@code null} if the
- * alias cannot be found.
- */
- public PrivateKey getPrivateKey(String alias);
-}
diff --git a/x-net/src/main/java/javax/net/ssl/X509TrustManager.java b/x-net/src/main/java/javax/net/ssl/X509TrustManager.java
deleted file mode 100644
index 7d7827e..0000000
--- a/x-net/src/main/java/javax/net/ssl/X509TrustManager.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package javax.net.ssl;
-
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-/**
- * The trust manager for X509 certificates to be used to perform authentication
- * for secure sockets.
- */
-public interface X509TrustManager extends TrustManager {
-
- /**
- * Checks whether the specified certificate chain (partial or complete) can
- * be validated and is trusted for client authentication for the specified
- * authentication type.
- *
- * @param chain
- * the certificate chain to validate.
- * @param authType
- * the authentication type used.
- * @throws CertificateException
- * if the certificate chain can't be validated or isn't trusted.
- * @throws IllegalArgumentException
- * if the specified certificate chain is empty or {@code null},
- * or if the specified authentication type is {@code null} or an
- * empty string.
- */
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException;
-
-
- /**
- * Checks whether the specified certificate chain (partial or complete) can
- * be validated and is trusted for server authentication for the specified
- * key exchange algorithm.
- *
- * @param chain
- * the certificate chain to validate.
- * @param authType
- * the key exchange algorithm name.
- * @throws CertificateException
- * if the certificate chain can't be validated or isn't trusted.
- * @throws IllegalArgumentException
- * if the specified certificate chain is empty or {@code null},
- * or if the specified authentication type is {@code null} or an
- * empty string.
- */
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException;
-
- /**
- * Returns the list of certificate issuer authorities which are trusted for
- * authentication of peers.
- *
- * @return the list of certificate issuer authorities which are trusted for
- * authentication of peers.
- */
- public X509Certificate[] getAcceptedIssuers();
-}
diff --git a/x-net/src/main/java/javax/net/ssl/package.html b/x-net/src/main/java/javax/net/ssl/package.html
deleted file mode 100644
index 14753c8..0000000
--- a/x-net/src/main/java/javax/net/ssl/package.html
+++ /dev/null
@@ -1,20 +0,0 @@
-<html>
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
-</head>
-<html>
-<body>
-<p>
-This package provides all the classes and interfaces needed to implement and program the Secure Socket
-abstraction based on the SSL protocol SSSLv3.0 or TLSv1.2.
-All the details of the SSL handshake protocol are accounted for, and a client or a server can specify the cipher
-set to use.
-
-X.509 certificates are verified, and, if desired, the client and the server each have the option of verifying
-the entire certificate chain until the root Certificate Authority is reached.
-
-Android uses code from The Legion of the Bouncy Castle (http://www.bouncycastle.org) and OpenSSL (http://openssl.org).
-
-</p>
-</body>
-</html>
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java
deleted file mode 100644
index 7a0985e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AbstractSessionContext.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.util.*;
-import java.util.logging.Level;
-import java.io.*;
-
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionContext;
-import javax.security.cert.X509Certificate;
-import javax.security.cert.CertificateEncodingException;
-import javax.security.cert.CertificateException;
-
-/**
- * Supports SSL session caches.
- */
-abstract class AbstractSessionContext implements SSLSessionContext {
-
- volatile int maximumSize;
- volatile int timeout;
-
- final int sslCtxNativePointer;
-
- /** Identifies OpenSSL sessions. */
- static final int OPEN_SSL = 1;
-
- /**
- * Constructs a new session context.
- *
- * @param sslCtxNativePointer Associated native SSL_CTX
- * @param maximumSize of cache
- * @param timeout for cache entries
- */
- AbstractSessionContext(int sslCtxNativePointer,
- int maximumSize, int timeout) {
- this.sslCtxNativePointer = sslCtxNativePointer;
- this.maximumSize = maximumSize;
- this.timeout = timeout;
- }
-
- /**
- * Returns the collection of sessions ordered by least-recently-used first.
- */
- abstract Iterator<SSLSession> sessionIterator();
-
- public final Enumeration getIds() {
- final Iterator<SSLSession> iterator = sessionIterator();
- return new Enumeration<byte[]>() {
- public boolean hasMoreElements() {
- return iterator.hasNext();
- }
- public byte[] nextElement() {
- return iterator.next().getId();
- }
- };
- }
-
- public final int getSessionCacheSize() {
- return maximumSize;
- }
-
- public final int getSessionTimeout() {
- return timeout;
- }
-
- /**
- * Makes sure cache size is < maximumSize.
- */
- abstract void trimToSize();
-
- public final void setSessionCacheSize(int size)
- throws IllegalArgumentException {
- if (size < 0) {
- throw new IllegalArgumentException("size < 0");
- }
-
- int oldMaximum = maximumSize;
- maximumSize = size;
-
- // Trim cache to size if necessary.
- if (size < oldMaximum) {
- trimToSize();
- }
- }
-
- /**
- * Converts the given session to bytes.
- *
- * @return session data as bytes or null if the session can't be converted
- */
- byte[] toBytes(SSLSession session) {
- // TODO: Support SSLSessionImpl, too.
- if (!(session instanceof OpenSSLSessionImpl)) {
- return null;
- }
-
- OpenSSLSessionImpl sslSession = (OpenSSLSessionImpl) session;
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputStream daos = new DataOutputStream(baos);
-
- daos.writeInt(OPEN_SSL); // session type ID
-
- // Session data.
- byte[] data = sslSession.getEncoded();
- daos.writeInt(data.length);
- daos.write(data);
-
- // Certificates.
- X509Certificate[] certs = session.getPeerCertificateChain();
- daos.writeInt(certs.length);
-
- // TODO: Call nativegetpeercertificates()
- for (X509Certificate cert : certs) {
- data = cert.getEncoded();
- daos.writeInt(data.length);
- daos.write(data);
- }
- // TODO: local certificates?
-
- return baos.toByteArray();
- } catch (IOException e) {
- log(e);
- return null;
- } catch (CertificateEncodingException e) {
- log(e);
- return null;
- }
- }
-
- /**
- * Creates a session from the given bytes.
- *
- * @return a session or null if the session can't be converted
- */
- SSLSession toSession(byte[] data, String host, int port) {
- ByteArrayInputStream bais = new ByteArrayInputStream(data);
- DataInputStream dais = new DataInputStream(bais);
- try {
- int type = dais.readInt();
- if (type != OPEN_SSL) {
- log(new AssertionError("Unexpected type ID: " + type));
- return null;
- }
-
- int length = dais.readInt();
- byte[] sessionData = new byte[length];
- dais.readFully(sessionData);
-
- int count = dais.readInt();
- X509Certificate[] certs = new X509Certificate[count];
- for (int i = 0; i < count; i++) {
- length = dais.readInt();
- byte[] certData = new byte[length];
- dais.readFully(certData);
- certs[i] = X509Certificate.getInstance(certData);
- }
-
- return new OpenSSLSessionImpl(sessionData, host, port, certs, this);
- } catch (IOException e) {
- log(e);
- return null;
- } catch (CertificateException e) {
- log(e);
- return null;
- }
- }
-
- /**
- * Puts an SSLSession in the AbstractSessionContext cache
- */
- abstract void putSession(SSLSession session);
-
- static void log(Throwable t) {
- java.util.logging.Logger.global.log(Level.WARNING,
- "Error converting session.", t);
- }
-
- protected void finalize() throws IOException {
- NativeCrypto.SSL_CTX_free(sslCtxNativePointer);
- }
-
- /**
- * Byte array wrapper. Implements equals() and hashCode().
- */
- static class ByteArray {
-
- private final byte[] bytes;
-
- ByteArray(byte[] bytes) {
- this.bytes = bytes;
- }
-
- @Override
- public int hashCode() {
- return Arrays.hashCode(bytes);
- }
-
- @Override
- @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
- public boolean equals(Object o) {
- ByteArray other = (ByteArray) o;
- return Arrays.equals(bytes, other.bytes);
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertException.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertException.java
deleted file mode 100644
index f607364..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertException.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLException;
-
-/**
- * This exception is used to signal that a fatal alert has occurred while working through the
- * protocol.
- */
-public class AlertException extends RuntimeException {
-
- private static final long serialVersionUID = -4448327177165687581L;
- // SSLException to be thrown to application side
- private final SSLException reason;
- // alert description code
- private final byte description;
-
- /**
- * Constructs the instance.
- *
- * @param description The alert description code from {@link AlertProtocol}
- * @param reason The SSLException to be thrown to application side after alert processing
- * (sending the record with alert, shutdown work, etc).
- * @see AlertProtocol
- */
- protected AlertException(byte description, SSLException reason) {
- super(reason);
- this.reason = reason;
- this.description = description;
- }
-
- /**
- * Returns the reason of alert. This reason should be rethrown after alert processing.
- *
- * @return the reason of alert.
- */
- protected SSLException getReason() {
- return reason;
- }
-
- /**
- * Returns alert's description code.
- *
- * @return alert description code from {@link AlertProtocol}
- * @see AlertProtocol for more information about possible reason codes.
- */
- protected byte getDescriptionCode() {
- return description;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertProtocol.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertProtocol.java
deleted file mode 100644
index a12d00a..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/AlertProtocol.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.SSLRecordProtocol;
-import org.apache.harmony.xnet.provider.jsse.Logger;
-import org.apache.harmony.xnet.provider.jsse.ContentType;
-
-/**
- * This class encapsulates the functionality of Alert Protocol.
- * Constant values are taken according to the TLS v1 specification
- * (http://www.ietf.org/rfc/rfc2246.txt), p 7.2.
- */
-public class AlertProtocol {
-
- // ------------------------ AlertLevel codes --------------------------
- /**
- * Defines the severity of alert as warning
- */
- protected static final byte WARNING = 1;
- /**
- * Defines the severity of alert as fatal
- */
- protected static final byte FATAL = 2;
-
- // --------------------- AlertDescription codes -----------------------
- /**
- * Defines the description code of the close_notify alert
- */
- protected static final byte CLOSE_NOTIFY = 0;
- /**
- * Defines the description code of the unexpected_message alert
- */
- protected static final byte UNEXPECTED_MESSAGE = 10;
- /**
- * Defines the description code of the bad_record_mac alert
- */
- protected static final byte BAD_RECORD_MAC = 20;
- /**
- * Defines the description code of the decryption_failed alert
- */
- protected static final byte DECRYPTION_FAILED = 21;
- /**
- * Defines the description code of the record_overflow alert
- */
- protected static final byte RECORD_OVERFLOW = 22;
- /**
- * Defines the description code of the decompression_failure alert
- */
- protected static final byte DECOMPRESSION_FAILURE = 30;
- /**
- * Defines the description code of the handshake_failure alert
- */
- protected static final byte HANDSHAKE_FAILURE = 40;
- /**
- * Defines the description code of the bad_certificate alert
- */
- protected static final byte BAD_CERTIFICATE = 42;
- /**
- * Defines the description code of the unsupported_certificate alert
- */
- protected static final byte UNSUPPORTED_CERTIFICATE = 43;
- /**
- * Defines the description code of the certificate_revoked alert
- */
- protected static final byte CERTIFICATE_REVOKED = 44;
- /**
- * Defines the description code of the certificate_expired alert
- */
- protected static final byte CERTIFICATE_EXPIRED = 45;
- /**
- * Defines the description code of the certificate_unknown alert
- */
- protected static final byte CERTIFICATE_UNKNOWN = 46;
- /**
- * Defines the description code of the illegal_parameter alert
- */
- protected static final byte ILLEGAL_PARAMETER = 47;
- /**
- * Defines the description code of the unknown_ca alert
- */
- protected static final byte UNKNOWN_CA = 48;
- /**
- * Defines the description code of the access_denied alert
- */
- protected static final byte ACCESS_DENIED = 49;
- /**
- * Defines the description code of the decode_error alert
- */
- protected static final byte DECODE_ERROR = 50;
- /**
- * Defines the description code of the decrypt_error alert
- */
- protected static final byte DECRYPT_ERROR = 51;
- /**
- * Defines the description code of the export_restriction alert
- */
- protected static final byte EXPORT_RESTRICTION = 60;
- /**
- * Defines the description code of the protocol_version alert
- */
- protected static final byte PROTOCOL_VERSION = 70;
- /**
- * Defines the description code of the insufficient_security alert
- */
- protected static final byte INSUFFICIENT_SECURITY = 71;
- /**
- * Defines the description code of the internal_error alert
- */
- protected static final byte INTERNAL_ERROR = 80;
- /**
- * Defines the description code of the user_canceled alert
- */
- protected static final byte USER_CANCELED = 90;
- /**
- * Defines the description code of the no_renegotiation alert
- */
- protected static final byte NO_RENEGOTIATION = 100;
- // holds level and description codes
- private final byte[] alert = new byte[2];
- // record protocol to be used to wrap the alerts
- private SSLRecordProtocol recordProtocol;
-
- private Logger.Stream logger = Logger.getStream("alert");
-
- /**
- * Creates the instance of AlertProtocol.
- * Note that class is not ready to work without providing of
- * record protocol
- * @see #setRecordProtocol
- */
- protected AlertProtocol() {}
-
- /**
- * Sets up the record protocol to be used by this allert protocol.
- */
- protected void setRecordProtocol(SSLRecordProtocol recordProtocol) {
- this.recordProtocol = recordProtocol;
- }
-
- /**
- * Reports an alert to be sent/received by transport.
- * This method is usually called during processing
- * of the income TSL record: if it contains alert message from another
- * peer, or if warning alert occured during the processing of the
- * message and this warning should be sent to another peer.
- * @param level: alert level code
- * @param description: alert description code
- * @return
- */
- protected void alert(byte level, byte description) {
- if (logger != null) {
- logger.println("Alert.alert: "+level+" "+description);
- }
- this.alert[0] = level;
- this.alert[1] = description;
- }
-
- /**
- * Returns the description code of alert or -100 if there
- * is no alert.
- */
- protected byte getDescriptionCode() {
- return (alert[0] != 0) ? alert[1] : -100;
- }
-
- /**
- * Resets the protocol to be in "no alert" state.
- * This method shoud be called after processing of the reported alert.
- */
- protected void setProcessed() {
- // free the info about alert
- if (logger != null) {
- logger.println("Alert.setProcessed");
- }
- this.alert[0] = 0;
- }
-
- /**
- * Checks if any alert has occured.
- */
- protected boolean hasAlert() {
- return (alert[0] != 0);
- }
-
- /**
- * Checks if occured alert is fatal alert.
- */
- protected boolean isFatalAlert() {
- return (alert[0] == 2);
- }
-
- /**
- * Returns the string representation of occured alert.
- * If no alert has occured null is returned.
- */
- protected String getAlertDescription() {
- switch (alert[1]) {
- case CLOSE_NOTIFY:
- return "close_notify";
- case UNEXPECTED_MESSAGE:
- return "unexpected_message";
- case BAD_RECORD_MAC:
- return "bad_record_mac";
- case DECRYPTION_FAILED:
- return "decryption_failed";
- case RECORD_OVERFLOW:
- return "record_overflow";
- case DECOMPRESSION_FAILURE:
- return "decompression_failure";
- case HANDSHAKE_FAILURE:
- return "handshake_failure";
- case BAD_CERTIFICATE:
- return "bad_certificate";
- case UNSUPPORTED_CERTIFICATE:
- return "unsupported_certificate";
- case CERTIFICATE_REVOKED:
- return "certificate_revoked";
- case CERTIFICATE_EXPIRED:
- return "certificate_expired";
- case CERTIFICATE_UNKNOWN:
- return "certificate_unknown";
- case ILLEGAL_PARAMETER:
- return "illegal_parameter";
- case UNKNOWN_CA:
- return "unknown_ca";
- case ACCESS_DENIED:
- return "access_denied";
- case DECODE_ERROR:
- return "decode_error";
- case DECRYPT_ERROR:
- return "decrypt_error";
- case EXPORT_RESTRICTION:
- return "export_restriction";
- case PROTOCOL_VERSION:
- return "protocol_version";
- case INSUFFICIENT_SECURITY:
- return "insufficient_security";
- case INTERNAL_ERROR:
- return "internal_error";
- case USER_CANCELED:
- return "user_canceled";
- case NO_RENEGOTIATION:
- return "no_renegotiation";
- }
- return null;
- }
-
- /**
- * Returns the record with reported alert message.
- * The returned array of bytes is ready to be sent to another peer.
- * Note, that this method does not automatically set the state of alert
- * protocol in "no alert" state, so after wrapping the method setProcessed
- * should be called.
- */
- protected byte[] wrap() {
- byte[] res = recordProtocol.wrap(ContentType.ALERT, alert, 0, 2);
- return res;
- }
-
- /**
- * Shutdown the protocol. It will be impossible to use the instance
- * after the calling of this method.
- */
- protected void shutdown() {
- alert[0] = 0;
- alert[1] = 0;
- recordProtocol = null;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Appendable.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Appendable.java
deleted file mode 100644
index 070f42a..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Appendable.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- * This interface represents the ability of the input stream related classes to provide additional
- * data to be read.
- */
-public interface Appendable {
-
- /**
- * Provides the additional data to be read.
- *
- * @param src the source data to be appended.
- */
- public void append(byte[] src);
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java
deleted file mode 100644
index 8065860..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateMessage.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-import org.apache.harmony.xnet.provider.jsse.AlertProtocol;
-
-import java.io.IOException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.X509Certificate;
-import java.util.Vector;
-
-/**
- * Represents server/client certificate message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS
- * 1.0 spec., 7.4.2. Server certificate; 7.4.6. Client certificate</a>
- *
- */
-public class CertificateMessage extends Message {
-
- /**
- * Certificates
- */
- X509Certificate[] certs;
-
- /**
- * Certificates in encoded form
- */
- byte[][] encoded_certs;
-
- /**
- * Creates inbound message
- *
- * @param in
- * @param length
- * @throws IOException
- */
- public CertificateMessage(HandshakeIODataStream in, int length)
- throws IOException {
- int l = in.readUint24(); // total_length
- if (l == 0) { // message contais no certificates
- if (length != 3) { // no more bytes after total_length
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateMessage");
- }
- certs = new X509Certificate[0];
- encoded_certs = new byte[0][0];
- this.length = 3;
- return;
- }
- CertificateFactory cf;
- try {
- cf = CertificateFactory.getInstance("X509");
- } catch (CertificateException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
- return;
- }
- Vector<Certificate> certs_vector = new Vector<Certificate>();
- int size = 0;
- int enc_size = 0;
- while (l > 0) {
- size = in.readUint24();
- l -= 3;
- try {
- certs_vector.add(cf.generateCertificate(in));
- } catch (CertificateException e) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR", e);
- }
- l -= size;
- enc_size += size;
- }
- certs = new X509Certificate[certs_vector.size()];
- for (int i = 0; i < certs.length; i++) {
- certs[i] = (X509Certificate) certs_vector.elementAt(i);
- }
- this.length = 3 + 3 * certs.length + enc_size;
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateMessage");
- }
-
- }
-
- /**
- * Creates outbound message
- *
- * @param certs
- */
- public CertificateMessage(X509Certificate[] certs) {
- if (certs == null) {
- this.certs = new X509Certificate[0];
- encoded_certs = new byte[0][0];
- length = 3;
- return;
- }
- this.certs = certs;
- if (encoded_certs == null) {
- encoded_certs = new byte[certs.length][];
- for (int i = 0; i < certs.length; i++) {
- try {
- encoded_certs[i] = certs[i].getEncoded();
- } catch (CertificateEncodingException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR",
- e);
- }
- }
- }
- length = 3 + 3 * encoded_certs.length;
- for (int i = 0; i < encoded_certs.length; i++) {
- length += encoded_certs[i].length;
- }
- }
-
- /**
- * Sends message
- *
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
-
- int total_length = 0;
- if (encoded_certs == null) {
- encoded_certs = new byte[certs.length][];
- for (int i = 0; i < certs.length; i++) {
- try {
- encoded_certs[i] = certs[i].getEncoded();
- } catch (CertificateEncodingException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR",
- e);
- }
- }
- }
- total_length = 3 * encoded_certs.length;
- for (int i = 0; i < encoded_certs.length; i++) {
- total_length += encoded_certs[i].length;
- }
- out.writeUint24(total_length);
- for (int i = 0; i < encoded_certs.length; i++) {
- out.writeUint24(encoded_certs[i].length);
- out.write(encoded_certs[i]);
- }
-
- }
-
- /**
- * Returns message type
- *
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CERTIFICATE;
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java
deleted file mode 100644
index 7246c4d..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateRequest.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-import org.apache.harmony.xnet.provider.jsse.AlertProtocol;
-
-import java.io.IOException;
-import java.security.cert.X509Certificate;
-import java.util.Vector;
-
-import javax.security.auth.x500.X500Principal;
-
-/**
- *
- * Represents certificate request message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.4.
- * Certificate request</a>
- */
-public class CertificateRequest extends Message {
-
- /**
- * Client certificate types as defined in
- * TLS 1.0 spec., 7.4.4. Certificate request
- */
- public static final byte RSA_SIGN = 1;
- public static final byte DSS_SIGN = 2;
- public static final byte RSA_FIXED_DH = 3;
- public static final byte DSS_FIXED_DH = 4;
-
- /**
- * Requested certificate types
- */
- final byte[] certificate_types;
-
- /**
- * Certificate authorities
- */
- X500Principal[] certificate_authorities;
-
- // Requested certificate types as Strings
- // ("RSA", "DSA", "DH_RSA" or "DH_DSA")
- private String[] types;
-
- // Encoded form of certificate authorities
- private byte[][] encoded_principals;
-
- /**
- * Creates outbound message
- *
- * @param certificate_types
- * @param accepted - array of certificate authority certificates
- */
- public CertificateRequest(byte[] certificate_types,
- X509Certificate[] accepted) {
-
- if (accepted == null) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "CertificateRequest: array of certificate authority certificates is null");
- }
- this.certificate_types = certificate_types;
-
- int totalPrincipalsLength = 0;
- certificate_authorities = new X500Principal[accepted.length];
- encoded_principals = new byte[accepted.length][];
- for (int i = 0; i < accepted.length; i++) {
- certificate_authorities[i] = accepted[i].getIssuerX500Principal();
- encoded_principals[i] = certificate_authorities[i].getEncoded();
- totalPrincipalsLength += encoded_principals[i].length + 2;
- }
-
- length = 3 + certificate_types.length + totalPrincipalsLength;
- }
-
- /**
- * Creates inbound message
- *
- * @param in
- * @param length
- * @throws IOException
- */
- public CertificateRequest(HandshakeIODataStream in, int length)
- throws IOException {
- int size = in.readUint8();
- certificate_types = new byte[size];
- in.read(certificate_types, 0, size);
- size = in.readUint16();
- certificate_authorities = new X500Principal[size];
- int totalPrincipalsLength = 0;
- int principalLength = 0;
- Vector<X500Principal> principals = new Vector<X500Principal>();
- while (totalPrincipalsLength < size) {
- principalLength = in.readUint16(); // encoded X500Principal size
- principals.add(new X500Principal(in));
- totalPrincipalsLength += 2;
- totalPrincipalsLength += principalLength;
- }
- certificate_authorities = new X500Principal[principals.size()];
- for (int i = 0; i < certificate_authorities.length; i++) {
- certificate_authorities[i] = principals.elementAt(i);
- }
- this.length = 3 + certificate_types.length + totalPrincipalsLength;
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateRequest");
- }
-
- }
-
- /**
- * Sends message
- *
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
-
- out.writeUint8(certificate_types.length);
- for (int i = 0; i < certificate_types.length; i++) {
- out.write(certificate_types[i]);
- }
- int authoritiesLength = 0;
- for (int i = 0; i < certificate_authorities.length; i++) {
- authoritiesLength += encoded_principals[i].length +2;
- }
- out.writeUint16(authoritiesLength);
- for (int i = 0; i < certificate_authorities.length; i++) {
- out.writeUint16(encoded_principals[i].length);
- out.write(encoded_principals[i]);
- }
- }
-
- /**
- * Returns message type
- *
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CERTIFICATE_REQUEST;
- }
-
- /**
- * Returns requested certificate types as array of strings
- */
- public String[] getTypesAsString() {
- if (types == null) {
- types = new String[certificate_types.length];
- for (int i = 0; i < types.length; i++) {
- switch (certificate_types[i]) {
- case 1:
- types[i] = "RSA";
- break;
- case 2:
- types[i] = "DSA";
- break;
- case 3:
- types[i] = "DH_RSA";
- break;
- case 4:
- types[i] = "DH_DSA";
- break;
- default:
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateRequest");
- }
- }
- }
- return types;
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateVerify.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateVerify.java
deleted file mode 100644
index 9b18ecb..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CertificateVerify.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-import org.apache.harmony.xnet.provider.jsse.AlertProtocol;
-
-import java.io.IOException;
-
-/**
- * Represents certificate verify message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.8.
- * Certificate verify</a>
- */
-public class CertificateVerify extends Message {
-
- /**
- * Signature
- */
- byte[] signedHash;
-
- /**
- * Creates outbound message
- *
- * @param hash
- */
- public CertificateVerify(byte[] hash) {
- if (hash == null || hash.length == 0) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "INTERNAL ERROR: incorrect certificate verify hash");
- }
- this.signedHash = hash;
- length = hash.length + 2;
- }
-
- /**
- * Creates inbound message
- *
- * @param in
- * @param length
- * @throws IOException
- */
- public CertificateVerify(HandshakeIODataStream in, int length)
- throws IOException {
- if (length == 0) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateVerify");
- } else {
- if (in.readUint16() != length - 2) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect CertificateVerify");
- }
- signedHash = in.read(length -2);
- }
- this.length = length;
- }
-
- /**
- * Sends message
- *
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- if (signedHash.length != 0) {
- out.writeUint16(signedHash.length);
- out.write(signedHash);
- }
- }
-
- /**
- * Returns message type
- *
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CERTIFICATE_VERIFY;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java
deleted file mode 100644
index f084195..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/CipherSuite.java
+++ /dev/null
@@ -1,610 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.GeneralSecurityException;
-import java.util.Hashtable;
-
-import javax.crypto.Cipher;
-
-/**
- * Represents Cipher Suite as defined in TLS 1.0 spec.,
- * A.5. The CipherSuite;
- * C. CipherSuite definitions.
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec.</a>
- *
- */
-public class CipherSuite {
-
- /**
- * true if this cipher suite is supported
- */
- boolean supported = true;
-
- /**
- * cipher suite key exchange
- */
- final int keyExchange;
-
- /**
- * cipher
- */
- final String cipherName;
-
- /**
- * Cipher information
- */
- final int keyMaterial;
- final int expandedKeyMaterial;
- final int effectiveKeyBytes;
- final int IVSize;
- final private int blockSize;
-
- // cipher suite code
- private final byte[] cipherSuiteCode;
-
- // cipher suite name
- private final String name;
-
- // true if cipher suite is exportable
- private final boolean isExportable;
-
- // Hash algorithm
- final private String hashName;
-
- // MAC algorithm
- final private String hmacName;
-
- // Hash size
- final private int hashSize;
-
- /**
- * key exchange values
- */
- static int KeyExchange_RSA = 1;
- static int KeyExchange_RSA_EXPORT = 2;
- static int KeyExchange_DHE_DSS = 3;
- static int KeyExchange_DHE_DSS_EXPORT = 4;
- static int KeyExchange_DHE_RSA = 5;
- static int KeyExchange_DHE_RSA_EXPORT = 6;
- static int KeyExchange_DH_DSS = 7;
- static int KeyExchange_DH_RSA = 8;
- static int KeyExchange_DH_anon = 9;
- static int KeyExchange_DH_anon_EXPORT = 10;
- static int KeyExchange_DH_DSS_EXPORT = 11;
- static int KeyExchange_DH_RSA_EXPORT = 12;
-
- /**
- * TLS cipher suite codes
- */
- static byte[] code_TLS_NULL_WITH_NULL_NULL = { 0x00, 0x00 };
- static byte[] code_TLS_RSA_WITH_NULL_MD5 = { 0x00, 0x01 };
- static byte[] code_TLS_RSA_WITH_NULL_SHA = { 0x00, 0x02 };
- static byte[] code_TLS_RSA_EXPORT_WITH_RC4_40_MD5 = { 0x00, 0x03 };
- static byte[] code_TLS_RSA_WITH_RC4_128_MD5 = { 0x00, 0x04 };
- static byte[] code_TLS_RSA_WITH_RC4_128_SHA = { 0x00, 0x05 };
- static byte[] code_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = { 0x00, 0x06 };
- static byte[] code_TLS_RSA_WITH_IDEA_CBC_SHA = { 0x00, 0x07 };
- static byte[] code_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x08 };
- static byte[] code_TLS_RSA_WITH_DES_CBC_SHA = { 0x00, 0x09 };
- static byte[] code_TLS_RSA_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x0A };
- static byte[] code_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x0B };
- static byte[] code_TLS_DH_DSS_WITH_DES_CBC_SHA = { 0x00, 0x0C };
- static byte[] code_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x0D };
- static byte[] code_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x0E };
- static byte[] code_TLS_DH_RSA_WITH_DES_CBC_SHA = { 0x00, 0x0F };
- static byte[] code_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x10 };
- static byte[] code_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x11 };
- static byte[] code_TLS_DHE_DSS_WITH_DES_CBC_SHA = { 0x00, 0x12 };
- static byte[] code_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x13 };
- static byte[] code_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x14 };
- static byte[] code_TLS_DHE_RSA_WITH_DES_CBC_SHA = { 0x00, 0x15 };
- static byte[] code_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x16 };
- static byte[] code_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = { 0x00, 0x17 };
- static byte[] code_TLS_DH_anon_WITH_RC4_128_MD5 = { 0x00, 0x18 };
- static byte[] code_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = { 0x00, 0x19 };
- static byte[] code_TLS_DH_anon_WITH_DES_CBC_SHA = { 0x00, 0x1A };
- static byte[] code_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = { 0x00, 0x1B };
-
- static CipherSuite TLS_NULL_WITH_NULL_NULL = new CipherSuite(
- "TLS_NULL_WITH_NULL_NULL", true, 0, null, null,
- code_TLS_NULL_WITH_NULL_NULL);
-
- static CipherSuite TLS_RSA_WITH_NULL_MD5 = new CipherSuite(
- "TLS_RSA_WITH_NULL_MD5", true, KeyExchange_RSA, null, "MD5",
- code_TLS_RSA_WITH_NULL_MD5);
-
- static CipherSuite TLS_RSA_WITH_NULL_SHA = new CipherSuite(
- "TLS_RSA_WITH_NULL_SHA", true, KeyExchange_RSA, null, "SHA",
- code_TLS_RSA_WITH_NULL_SHA);
-
- static CipherSuite TLS_RSA_EXPORT_WITH_RC4_40_MD5 = new CipherSuite(
- "TLS_RSA_EXPORT_WITH_RC4_40_MD5", true, KeyExchange_RSA_EXPORT,
- "RC4_40", "MD5", code_TLS_RSA_EXPORT_WITH_RC4_40_MD5);
-
- static CipherSuite TLS_RSA_WITH_RC4_128_MD5 = new CipherSuite(
- "TLS_RSA_WITH_RC4_128_MD5", false, KeyExchange_RSA, "RC4_128",
- "MD5", code_TLS_RSA_WITH_RC4_128_MD5);
-
- static CipherSuite TLS_RSA_WITH_RC4_128_SHA = new CipherSuite(
- "TLS_RSA_WITH_RC4_128_SHA", false, KeyExchange_RSA, "RC4_128",
- "SHA", code_TLS_RSA_WITH_RC4_128_SHA);
-
- static CipherSuite TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5 = new CipherSuite(
- "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", true, KeyExchange_RSA_EXPORT,
- "RC2_CBC_40", "MD5", code_TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5);
-
- static CipherSuite TLS_RSA_WITH_IDEA_CBC_SHA = new CipherSuite(
- "TLS_RSA_WITH_IDEA_CBC_SHA", false, KeyExchange_RSA, "IDEA_CBC",
- "SHA", code_TLS_RSA_WITH_IDEA_CBC_SHA);
-
- static CipherSuite TLS_RSA_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", true, KeyExchange_RSA_EXPORT,
- "DES40_CBC", "SHA", code_TLS_RSA_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_RSA_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_RSA_WITH_DES_CBC_SHA", false, KeyExchange_RSA, "DES_CBC",
- "SHA", code_TLS_RSA_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_RSA_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_RSA_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_RSA,
- "3DES_EDE_CBC", "SHA", code_TLS_RSA_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DH_DSS_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DH_DSS_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DH_DSS_WITH_DES_CBC_SHA", false, KeyExchange_DH_DSS,
- "DES_CBC", "SHA", code_TLS_DH_DSS_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DH_DSS,
- "3DES_EDE_CBC", "SHA", code_TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DH_RSA_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DH_RSA_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DH_RSA_WITH_DES_CBC_SHA", false, KeyExchange_DH_RSA,
- "DES_CBC", "SHA", code_TLS_DH_RSA_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DH_RSA,
- "3DES_EDE_CBC", "SHA", code_TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DHE_DSS_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DHE_DSS_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DHE_DSS_WITH_DES_CBC_SHA", false, KeyExchange_DHE_DSS,
- "DES_CBC", "SHA", code_TLS_DHE_DSS_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DHE_DSS,
- "3DES_EDE_CBC", "SHA", code_TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DHE_RSA_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DHE_RSA_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DHE_RSA_WITH_DES_CBC_SHA", false, KeyExchange_DHE_RSA,
- "DES_CBC", "SHA", code_TLS_DHE_RSA_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DHE_RSA,
- "3DES_EDE_CBC", "SHA", code_TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA);
-
- static CipherSuite TLS_DH_anon_EXPORT_WITH_RC4_40_MD5 = new CipherSuite(
- "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", true,
- KeyExchange_DH_anon_EXPORT, "RC4_40", "MD5",
- code_TLS_DH_anon_EXPORT_WITH_RC4_40_MD5);
-
- static CipherSuite TLS_DH_anon_WITH_RC4_128_MD5 = new CipherSuite(
- "TLS_DH_anon_WITH_RC4_128_MD5", false, KeyExchange_DH_anon,
- "RC4_128", "MD5", code_TLS_DH_anon_WITH_RC4_128_MD5);
-
- static CipherSuite TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA = new CipherSuite(
- "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", true,
- KeyExchange_DH_anon_EXPORT, "DES40_CBC", "SHA",
- code_TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA);
-
- static CipherSuite TLS_DH_anon_WITH_DES_CBC_SHA = new CipherSuite(
- "TLS_DH_anon_WITH_DES_CBC_SHA", false, KeyExchange_DH_anon,
- "DES_CBC", "SHA", code_TLS_DH_anon_WITH_DES_CBC_SHA);
-
- static CipherSuite TLS_DH_anon_WITH_3DES_EDE_CBC_SHA = new CipherSuite(
- "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA", false, KeyExchange_DH_anon,
- "3DES_EDE_CBC", "SHA", code_TLS_DH_anon_WITH_3DES_EDE_CBC_SHA);
-
- // array for quick access to cipher suite by code
- private static CipherSuite[] cuitesByCode = {
- TLS_NULL_WITH_NULL_NULL,
- TLS_RSA_WITH_NULL_MD5,
- TLS_RSA_WITH_NULL_SHA,
- TLS_RSA_EXPORT_WITH_RC4_40_MD5,
- TLS_RSA_WITH_RC4_128_MD5,
- TLS_RSA_WITH_RC4_128_SHA,
- TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
- TLS_RSA_WITH_IDEA_CBC_SHA,
- TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_RSA_WITH_DES_CBC_SHA,
- TLS_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DH_DSS_WITH_DES_CBC_SHA,
- TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA,
- TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DH_RSA_WITH_DES_CBC_SHA,
- TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DHE_DSS_WITH_DES_CBC_SHA,
- TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
- TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DHE_RSA_WITH_DES_CBC_SHA,
- TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DH_anon_EXPORT_WITH_RC4_40_MD5,
- TLS_DH_anon_WITH_RC4_128_MD5,
- TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DH_anon_WITH_DES_CBC_SHA,
- TLS_DH_anon_WITH_3DES_EDE_CBC_SHA
- };
-
- // hash for quick access to cipher suite by name
- private static Hashtable<String, CipherSuite> cuitesByName;
-
- /**
- * array of supported cipher suites.
- * Set of supported suites is defined at the moment provider's start
- */
-// TODO Dynamically supported suites: new providers may be dynamically
-// added/removed and the set of supported suites may be changed
- static CipherSuite[] supportedCipherSuites;
-
- /**
- * array of supported cipher suites names
- */
- static String[] supportedCipherSuiteNames;
-
- /**
- * default cipher suites
- */
- static CipherSuite[] defaultCipherSuites;
-
- static {
- int count = 0;
- cuitesByName = new Hashtable<String, CipherSuite>();
- for (int i = 0; i < cuitesByCode.length; i++) {
- cuitesByName.put(cuitesByCode[i].getName(), cuitesByCode[i]);
- if (cuitesByCode[i].supported) {
- count++;
- }
- }
- supportedCipherSuites = new CipherSuite[count];
- supportedCipherSuiteNames = new String[count];
- count = 0;
- for (int i = 0; i < cuitesByCode.length; i++) {
- if (cuitesByCode[i].supported) {
- supportedCipherSuites[count] = cuitesByCode[i];
- supportedCipherSuiteNames[count] = supportedCipherSuites[count].getName();
- count++;
- }
- }
-
- CipherSuite[] defaultPretendent = {
- TLS_RSA_WITH_RC4_128_MD5,
- TLS_RSA_WITH_RC4_128_SHA,
- // TLS_RSA_WITH_AES_128_CBC_SHA,
- // TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
- // LS_DHE_DSS_WITH_AES_128_CBC_SHA,
- TLS_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
- TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_RSA_WITH_DES_CBC_SHA,
- TLS_DHE_RSA_WITH_DES_CBC_SHA, TLS_DHE_DSS_WITH_DES_CBC_SHA,
- TLS_RSA_EXPORT_WITH_RC4_40_MD5,
- TLS_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA,
- TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
- };
- count = 0;
- for (int i = 0; i < defaultPretendent.length; i++) {
- if (defaultPretendent[i].supported) {
- count++;
- }
- }
- defaultCipherSuites = new CipherSuite[count];
- count = 0;
- for (int i = 0; i < defaultPretendent.length; i++) {
- if (defaultPretendent[i].supported) {
- defaultCipherSuites[count++] = defaultPretendent[i];
- }
- }
- }
-
- /**
- * Returns CipherSuite by name
- * @param name
- * @return
- */
- public static CipherSuite getByName(String name) {
- return cuitesByName.get(name);
- }
-
- /**
- * Returns CipherSuite based on TLS CipherSuite code
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., A.5. The CipherSuite</a>
- * @param b1
- * @param b2
- * @return
- */
- public static CipherSuite getByCode(byte b1, byte b2) {
- if (b1 != 0 || (b2 & 0xFF) > cuitesByCode.length) {
- // Unknown
- return new CipherSuite("UNKNOUN_" + b1 + "_" + b2, false, 0, "",
- "", new byte[] { b1, b2 });
- }
- return cuitesByCode[b2];
- }
-
- /**
- * Returns CipherSuite based on V2CipherSpec code
- * as described in TLS 1.0 spec., E. Backward Compatibility With SSL
- *
- * @param b1
- * @param b2
- * @param b3
- * @return CipherSuite
- */
- public static CipherSuite getByCode(byte b1, byte b2, byte b3) {
- if (b1 == 0 && b2 == 0) {
- if ((b3 & 0xFF) <= cuitesByCode.length) {
- return cuitesByCode[b3];
- }
- }
- // as TLSv1 equivalent of V2CipherSpec should be included in
- // V2ClientHello, ignore V2CipherSpec
- return new CipherSuite("UNKNOUN_" + b1 + "_" + b2 + "_" + b3, false, 0,
- "", "", new byte[] { b1, b2, b3 });
- }
-
- /**
- * Creates CipherSuite
- * @param name
- * @param isExportable
- * @param keyExchange
- * @param cipherName
- * @param hash
- * @param code
- */
- public CipherSuite(String name, boolean isExportable, int keyExchange,
- String cipherName, String hash, byte[] code) {
- this.name = name;
- this.keyExchange = keyExchange;
- this.isExportable = isExportable;
- if (cipherName == null) {
- this.cipherName = null;
- keyMaterial = 0;
- expandedKeyMaterial = 0;
- effectiveKeyBytes = 0;
- IVSize = 0;
- blockSize = 0;
- } else if ("IDEA_CBC".equals(cipherName)) {
- this.cipherName = "IDEA/CBC/NoPadding";
- keyMaterial = 16;
- expandedKeyMaterial = 16;
- effectiveKeyBytes = 16;
- IVSize = 8;
- blockSize = 8;
- } else if ("RC2_CBC_40".equals(cipherName)) {
- this.cipherName = "RC2/CBC/NoPadding";
- keyMaterial = 5;
- expandedKeyMaterial = 16;
- effectiveKeyBytes = 5;
- IVSize = 8;
- blockSize = 8;
- } else if ("RC4_40".equals(cipherName)) {
- this.cipherName = "RC4";
- keyMaterial = 5;
- expandedKeyMaterial = 16;
- effectiveKeyBytes = 5;
- IVSize = 0;
- blockSize = 0;
- } else if ("RC4_128".equals(cipherName)) {
- this.cipherName = "RC4";
- keyMaterial = 16;
- expandedKeyMaterial = 16;
- effectiveKeyBytes = 16;
- IVSize = 0;
- blockSize = 0;
- } else if ("DES40_CBC".equals(cipherName)) {
- this.cipherName = "DES/CBC/NoPadding";
- keyMaterial = 5;
- expandedKeyMaterial = 8;
- effectiveKeyBytes = 5;
- IVSize = 8;
- blockSize = 8;
- } else if ("DES_CBC".equals(cipherName)) {
- this.cipherName = "DES/CBC/NoPadding";
- keyMaterial = 8;
- expandedKeyMaterial = 8;
- effectiveKeyBytes = 7;
- IVSize = 8;
- blockSize = 8;
- } else if ("3DES_EDE_CBC".equals(cipherName)) {
- this.cipherName = "DESede/CBC/NoPadding";
- keyMaterial = 24;
- expandedKeyMaterial = 24;
- effectiveKeyBytes = 24;
- IVSize = 8;
- blockSize = 8;
- } else {
- this.cipherName = cipherName;
- keyMaterial = 0;
- expandedKeyMaterial = 0;
- effectiveKeyBytes = 0;
- IVSize = 0;
- blockSize = 0;
- }
-
- if ("MD5".equals(hash)) {
- this.hmacName = "HmacMD5";
- this.hashName = "MD5";
- hashSize = 16;
- } else if ("SHA".equals(hash)) {
- this.hmacName = "HmacSHA1";
- this.hashName = "SHA-1";
- hashSize = 20;
- } else {
- this.hmacName = null;
- this.hashName = null;
- hashSize = 0;
- }
-
- cipherSuiteCode = code;
-
- if (this.cipherName != null) {
- try {
- Cipher.getInstance(this.cipherName);
- } catch (GeneralSecurityException e) {
- supported = false;
- }
- }
-
- }
-
- /**
- * Returns true if cipher suite is anonymous
- * @return
- */
- public boolean isAnonymous() {
- if (keyExchange == KeyExchange_DH_anon
- || keyExchange == KeyExchange_DH_anon_EXPORT) {
- return true;
- }
- return false;
- }
-
- /**
- * Returns array of supported CipherSuites
- * @return
- */
- public static CipherSuite[] getSupported() {
- return supportedCipherSuites;
- }
-
- /**
- * Returns array of supported cipher suites names
- * @return
- */
- public static String[] getSupportedCipherSuiteNames() {
- return supportedCipherSuiteNames.clone();
- }
-
- /**
- * Returns cipher suite name
- * @return
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns cipher suite code as byte array
- * @return
- */
- public byte[] toBytes() {
- return cipherSuiteCode;
- }
-
- /**
- * Returns cipher suite description
- */
- @Override
- public String toString() {
- return name + ": " + cipherSuiteCode[0] + " " + cipherSuiteCode[1];
- }
-
- /**
- * Compares this cipher suite to the specified object.
- */
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof CipherSuite
- && this.cipherSuiteCode[0] == ((CipherSuite) obj).cipherSuiteCode[0]
- && this.cipherSuiteCode[1] == ((CipherSuite) obj).cipherSuiteCode[1]) {
- return true;
- }
- return false;
- }
-
- /**
- * Returns cipher algorithm name
- * @return
- */
- public String getBulkEncryptionAlgorithm() {
- return cipherName;
- }
-
- /**
- * Returns cipher block size
- * @return
- */
- public int getBlockSize() {
- return blockSize;
- }
-
- /**
- * Returns MAC algorithm name
- * @return
- */
- public String getHmacName() {
- return hmacName;
- }
-
- /**
- * Returns hash algorithm name
- * @return
- */
- public String getHashName() {
- return hashName;
- }
-
- /**
- * Returns hash size
- * @return
- */
- public int getMACLength() {
- return hashSize;
- }
-
- /**
- * Indicates whether this cipher suite is exportable
- * @return
- */
- public boolean isExportable() {
- return isExportable;
- }
-
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java
deleted file mode 100644
index 34252f0..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHandshakeImpl.java
+++ /dev/null
@@ -1,629 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.Key;
-import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PrivilegedExceptionAction;
-import java.security.PublicKey;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Enumeration;
-
-import javax.crypto.Cipher;
-import javax.crypto.KeyAgreement;
-import javax.crypto.interfaces.DHKey;
-import javax.crypto.interfaces.DHPublicKey;
-import javax.crypto.spec.DHParameterSpec;
-import javax.crypto.spec.DHPublicKeySpec;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.X509ExtendedKeyManager;
-
-/**
- * Client side handshake protocol implementation.
- * Handshake protocol operates on top of the Record Protocol.
- * It is responsible for session negotiating.
- *
- * The implementation processes inbound server handshake messages,
- * creates and sends respond messages. Outbound messages are supplied
- * to Record Protocol. Detected errors are reported to the Alert protocol.
- *
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7. The
- * TLS Handshake Protocol</a>
- *
- */
-public class ClientHandshakeImpl extends HandshakeProtocol {
-
- /**
- * Creates Client Handshake Implementation
- *
- * @param owner
- */
- ClientHandshakeImpl(Object owner) {
- super(owner);
- }
-
- /**
- * Starts handshake
- *
- */
- @Override
- public void start() {
- if (session == null) { // initial handshake
- session = findSessionToResume();
- } else { // start session renegotiation
- if (clientHello != null && this.status != FINISHED) {
- // current negotiation has not completed
- return; // ignore
- }
- if (!session.isValid()) {
- session = null;
- }
- }
- if (session != null) {
- isResuming = true;
- } else if (parameters.getEnableSessionCreation()){
- isResuming = false;
- session = new SSLSessionImpl(parameters.getSecureRandom());
- session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
- session.protocol = ProtocolVersion.getLatestVersion(parameters
- .getEnabledProtocols());
- recordProtocol.setVersion(session.protocol.version);
- } else {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created ");
- }
- startSession();
- }
-
- /**
- * Starts renegotiation on a new session
- *
- */
- private void renegotiateNewSession() {
- if (parameters.getEnableSessionCreation()){
- isResuming = false;
- session = new SSLSessionImpl(parameters.getSecureRandom());
- session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
- session.protocol = ProtocolVersion.getLatestVersion(parameters
- .getEnabledProtocols());
- recordProtocol.setVersion(session.protocol.version);
- startSession();
- } else {
- status = NOT_HANDSHAKING;
- sendWarningAlert(AlertProtocol.NO_RENEGOTIATION);
- }
- }
-
- /*
- * Starts/resumes session
- */
- private void startSession() {
- CipherSuite[] cipher_suites;
- if (isResuming) {
- cipher_suites = new CipherSuite[] { session.cipherSuite };
- } else {
- // BEGIN android-changed
- cipher_suites = parameters.getEnabledCipherSuitesMember();
- // END android-changed
- }
- clientHello = new ClientHello(parameters.getSecureRandom(),
- session.protocol.version, session.id, cipher_suites);
- session.clientRandom = clientHello.random;
- send(clientHello);
- status = NEED_UNWRAP;
- }
-
- /**
- * Processes inbound handshake messages
- * @param bytes
- */
- @Override
- public void unwrap(byte[] bytes) {
- if (this.delegatedTaskErr != null) {
- Exception e = this.delegatedTaskErr;
- this.delegatedTaskErr = null;
- this.fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "Error in delegated task", e);
- }
- int handshakeType;
- io_stream.append(bytes);
- while (io_stream.available() > 0) {
- io_stream.mark();
- int length;
- try {
- handshakeType = io_stream.read();
- length = io_stream.readUint24();
- if (io_stream.available() < length) {
- io_stream.reset();
- return;
- }
- switch (handshakeType) {
- case 0: // HELLO_REQUEST
- // we don't need to take this message into account
- // during FINISH message verification, so remove it
- io_stream.removeFromMarkedPosition();
- if (clientHello != null
- && (clientFinished == null || serverFinished == null)) {
- //currently negotiating - ignore
- break;
- }
- // renegotiate
- if (session.isValid()) {
- session = (SSLSessionImpl) session.clone();
- isResuming = true;
- startSession();
- } else {
- // if SSLSession is invalidated (e.g. timeout limit is
- // exceeded) connection can't resume the session.
- renegotiateNewSession();
- }
- break;
- case 2: // SERVER_HELLO
- if (clientHello == null || serverHello != null) {
- unexpectedMessage();
- return;
- }
- serverHello = new ServerHello(io_stream, length);
-
- //check protocol version
- ProtocolVersion servProt = ProtocolVersion
- .getByVersion(serverHello.server_version);
- String[] enabled = parameters.getEnabledProtocols();
- find: {
- for (int i = 0; i < enabled.length; i++) {
- if (servProt.equals(ProtocolVersion
- .getByName(enabled[i]))) {
- break find;
- }
- }
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello protocol version");
- }
-
- // check compression method
- if (serverHello.compression_method != 0) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello compression method");
- }
-
- //check cipher_suite
- // BEGIN android-changed
- CipherSuite[] enabledSuites = parameters.getEnabledCipherSuitesMember();
- // END android-changed
- find: {
- for (int i = 0; i < enabledSuites.length; i++) {
- if (serverHello.cipher_suite
- .equals(enabledSuites[i])) {
- break find;
- }
- }
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello cipher suite");
- }
-
- if (isResuming) {
- if (serverHello.session_id.length == 0) {
- // server is not willing to establish the new connection
- // using specified session
- isResuming = false;
- } else if (!Arrays.equals(serverHello.session_id, clientHello.session_id)) {
- isResuming = false;
- } else if (!session.protocol.equals(servProt)) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello protocol version");
- } else if (!session.cipherSuite
- .equals(serverHello.cipher_suite)) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Bad server hello cipher suite");
- }
- if (serverHello.server_version[1] == 1) {
- computerReferenceVerifyDataTLS("server finished");
- } else {
- computerReferenceVerifyDataSSLv3(SSLv3Constants.server);
- }
- }
- session.protocol = servProt;
- recordProtocol.setVersion(session.protocol.version);
- session.cipherSuite = serverHello.cipher_suite;
- session.id = serverHello.session_id.clone();
- session.serverRandom = serverHello.random;
- break;
- case 11: // CERTIFICATE
- if (serverHello == null || serverKeyExchange != null
- || serverCert != null || isResuming) {
- unexpectedMessage();
- return;
- }
- serverCert = new CertificateMessage(io_stream, length);
- break;
- case 12: // SERVER_KEY_EXCHANGE
- if (serverHello == null || serverKeyExchange != null
- || isResuming) {
- unexpectedMessage();
- return;
- }
- serverKeyExchange = new ServerKeyExchange(io_stream,
- length, session.cipherSuite.keyExchange);
- break;
- case 13: // CERTIFICATE_REQUEST
- if (serverCert == null || certificateRequest != null
- || session.cipherSuite.isAnonymous() || isResuming) {
- unexpectedMessage();
- return;
- }
- certificateRequest = new CertificateRequest(io_stream,
- length);
- break;
- case 14: // SERVER_HELLO_DONE
- if (serverHello == null || serverHelloDone != null
- || isResuming) {
- unexpectedMessage();
- return;
- }
- serverHelloDone = new ServerHelloDone(io_stream, length);
- if (this.nonBlocking) {
- delegatedTasks.add(new DelegatedTask(new PrivilegedExceptionAction<Void>() {
- public Void run() throws Exception {
- processServerHelloDone();
- return null;
- }
- }, this, AccessController.getContext()));
- return;
- }
- processServerHelloDone();
- break;
- case 20: // FINISHED
- if (!changeCipherSpecReceived) {
- unexpectedMessage();
- return;
- }
- serverFinished = new Finished(io_stream, length);
- verifyFinished(serverFinished.getData());
- session.lastAccessedTime = System.currentTimeMillis();
- // BEGIN android-added
- session.context = parameters.getClientSessionContext();
- // END android-added
- parameters.getClientSessionContext().putSession(session);
- if (isResuming) {
- sendChangeCipherSpec();
- } else {
- session.lastAccessedTime = System.currentTimeMillis();
- status = FINISHED;
- }
- // XXX there is no cleanup work
- break;
- default:
- unexpectedMessage();
- return;
- }
- } catch (IOException e) {
- // io stream dosn't contain complete handshake message
- io_stream.reset();
- return;
- }
- }
-
- }
-
- /**
- * Processes SSLv2 Hello message.
- * SSLv2 client hello message message is an unexpected message
- * for client side of handshake protocol.
- * @ see TLS 1.0 spec., E.1. Version 2 client hello
- * @param bytes
- */
- @Override
- public void unwrapSSLv2(byte[] bytes) {
- unexpectedMessage();
- }
-
- /**
- * Creates and sends Finished message
- */
- @Override
- protected void makeFinished() {
- byte[] verify_data;
- if (serverHello.server_version[1] == 1) {
- verify_data = new byte[12];
- computerVerifyDataTLS("client finished", verify_data);
- } else {
- verify_data = new byte[36];
- computerVerifyDataSSLv3(SSLv3Constants.client, verify_data);
- }
- clientFinished = new Finished(verify_data);
- send(clientFinished);
- if (isResuming) {
- session.lastAccessedTime = System.currentTimeMillis();
- status = FINISHED;
- } else {
- if (serverHello.server_version[1] == 1) {
- computerReferenceVerifyDataTLS("server finished");
- } else {
- computerReferenceVerifyDataSSLv3(SSLv3Constants.server);
- }
- status = NEED_UNWRAP;
- }
- }
-
- /**
- * Processes ServerHelloDone: makes verification of the server messages; sends
- * client messages, computers masterSecret, sends ChangeCipherSpec
- */
- void processServerHelloDone() {
- PrivateKey clientKey = null;
-
- if (serverCert != null) {
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon_EXPORT) {
- unexpectedMessage();
- return;
- }
- verifyServerCert();
- } else {
- if (session.cipherSuite.keyExchange != CipherSuite.KeyExchange_DH_anon
- && session.cipherSuite.keyExchange != CipherSuite.KeyExchange_DH_anon_EXPORT) {
- unexpectedMessage();
- return;
- }
- }
-
- // Client certificate
- if (certificateRequest != null) {
- X509Certificate[] certs = null;
- String clientAlias = ((X509ExtendedKeyManager) parameters
- .getKeyManager()).chooseClientAlias(certificateRequest
- .getTypesAsString(),
- certificateRequest.certificate_authorities, null);
- if (clientAlias != null) {
- X509ExtendedKeyManager km = (X509ExtendedKeyManager) parameters
- .getKeyManager();
- certs = km.getCertificateChain((clientAlias));
- clientKey = km.getPrivateKey(clientAlias);
- }
- session.localCertificates = certs;
- clientCert = new CertificateMessage(certs);
- send(clientCert);
- }
- // Client key exchange
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- // RSA encrypted premaster secret message
- Cipher c;
- try {
- c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
- if (serverKeyExchange != null) {
- c.init(Cipher.ENCRYPT_MODE, serverKeyExchange
- .getRSAPublicKey());
- } else {
- c.init(Cipher.ENCRYPT_MODE, serverCert.certs[0]);
- }
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "Unexpected exception", e);
- return;
- }
- preMasterSecret = new byte[48];
- parameters.getSecureRandom().nextBytes(preMasterSecret);
- System.arraycopy(clientHello.client_version, 0, preMasterSecret, 0,
- 2);
- try {
- clientKeyExchange = new ClientKeyExchange(c
- .doFinal(preMasterSecret),
- serverHello.server_version[1] == 1);
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "Unexpected exception", e);
- return;
- }
- } else {
- PublicKey serverPublic;
- KeyAgreement agreement = null;
- DHParameterSpec spec;
- try {
- KeyFactory kf = null;
- try {
- kf = KeyFactory.getInstance("DH");
- } catch (NoSuchAlgorithmException e) {
- kf = KeyFactory.getInstance("DiffieHellman");
- }
-
- try {
- agreement = KeyAgreement.getInstance("DH");
- } catch (NoSuchAlgorithmException ee) {
- agreement = KeyAgreement.getInstance("DiffieHellman");
- }
-
- KeyPairGenerator kpg = null;
- try {
- kpg = KeyPairGenerator.getInstance("DH");
- } catch (NoSuchAlgorithmException e) {
- kpg = KeyPairGenerator.getInstance("DiffieHellman");
- }
- if (serverKeyExchange != null) {
- serverPublic = kf.generatePublic(new DHPublicKeySpec(
- serverKeyExchange.par3, serverKeyExchange.par1,
- serverKeyExchange.par2));
- spec = new DHParameterSpec(serverKeyExchange.par1,
- serverKeyExchange.par2);
- } else {
- serverPublic = serverCert.certs[0].getPublicKey();
- spec = ((DHPublicKey) serverPublic).getParams();
- }
- kpg.initialize(spec);
-
- KeyPair kp = kpg.generateKeyPair();
- Key key = kp.getPublic();
- if (clientCert != null
- && serverCert != null
- && (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS)) {
- PublicKey client_pk = clientCert.certs[0].getPublicKey();
- PublicKey server_pk = serverCert.certs[0].getPublicKey();
- if (client_pk instanceof DHKey
- && server_pk instanceof DHKey) {
- if (((DHKey) client_pk).getParams().getG().equals(
- ((DHKey) server_pk).getParams().getG())
- && ((DHKey) client_pk).getParams().getP()
- .equals(((DHKey) server_pk).getParams().getG())) {
- // client cert message DH public key parameters
- // matched those specified by the
- // server in its certificate,
- clientKeyExchange = new ClientKeyExchange(); // empty
- }
- }
- } else {
- clientKeyExchange = new ClientKeyExchange(
- ((DHPublicKey) key).getY());
- }
- key = kp.getPrivate();
- agreement.init(key);
- agreement.doPhase(serverPublic, true);
- preMasterSecret = agreement.generateSecret();
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "Unexpected exception", e);
- return;
- }
- }
- if (clientKeyExchange != null) {
- send(clientKeyExchange);
- }
-
- computerMasterSecret();
-
- // send certificate verify for all certificates except those containing
- // fixed DH parameters
- if (clientCert != null && !clientKeyExchange.isEmpty()) {
- // Certificate verify
- DigitalSignature ds = new DigitalSignature(
- session.cipherSuite.keyExchange);
- ds.init(clientKey);
-
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT) {
- ds.setMD5(io_stream.getDigestMD5());
- ds.setSHA(io_stream.getDigestSHA());
- } else if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT) {
- ds.setSHA(io_stream.getDigestSHA());
- // The Signature should be empty in case of anonimous signature algorithm:
- // } else if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon ||
- // session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon_EXPORT) {
- }
- certificateVerify = new CertificateVerify(ds.sign());
- send(certificateVerify);
- }
-
- sendChangeCipherSpec();
- }
-
- /*
- * Verifies certificate path
- */
- private void verifyServerCert() {
- String authType = null;
- switch (session.cipherSuite.keyExchange) {
- case 1: // KeyExchange_RSA
- authType = "RSA";
- break;
- case 2: // KeyExchange_RSA_EXPORT
- if (serverKeyExchange != null ) {
- // ephemeral RSA key is used
- authType = "RSA_EXPORT";
- } else {
- authType = "RSA";
- }
- break;
- case 3: // KeyExchange_DHE_DSS
- case 4: // KeyExchange_DHE_DSS_EXPORT
- authType = "DHE_DSS";
- break;
- case 5: // KeyExchange_DHE_RSA
- case 6: // KeyExchange_DHE_RSA_EXPORT
- authType = "DHE_RSA";
- break;
- case 7: // KeyExchange_DH_DSS
- case 11: // KeyExchange_DH_DSS_EXPORT
- authType = "DH_DSS";
- break;
- case 8: // KeyExchange_DH_RSA
- case 12: // KeyExchange_DH_RSA_EXPORT
- authType = "DH_RSA";
- break;
- case 9: // KeyExchange_DH_anon
- case 10: // KeyExchange_DH_anon_EXPORT
- return;
- }
- try {
- parameters.getTrustManager().checkServerTrusted(serverCert.certs,
- authType);
- } catch (CertificateException e) {
- fatalAlert(AlertProtocol.BAD_CERTIFICATE, "Not trusted server certificate", e);
- return;
- }
- session.peerCertificates = serverCert.certs;
- }
-
- /**
- * Processes ChangeCipherSpec message
- */
- @Override
- public void receiveChangeCipherSpec() {
- if (isResuming) {
- if (serverHello == null) {
- unexpectedMessage();
- }
- } else if (clientFinished == null) {
- unexpectedMessage();
- }
- changeCipherSpecReceived = true;
- }
-
- // Find session to resume in client session context
- private SSLSessionImpl findSessionToResume() {
- // BEGIN android-changed
- String host = null;
- int port = -1;
- if (engineOwner != null) {
- host = engineOwner.getPeerHost();
- port = engineOwner.getPeerPort();
- }
- if (host == null || port == -1) {
- return null; // starts new session
- }
-
- ClientSessionContext context = parameters.getClientSessionContext();
- SSLSessionImpl session
- = (SSLSessionImpl) context.getSession(host, port);
- if (session != null) {
- session = (SSLSessionImpl) session.clone();
- }
- return session;
- // END android-changed
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHello.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHello.java
deleted file mode 100644
index 5764105..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientHello.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.security.SecureRandom;
-import java.util.Arrays;
-
-/**
- * Represents Client Hello message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.1.2.
- * Client hello</a>
- *
- */
-public class ClientHello extends Message {
-
- /**
- * Client version
- */
- final byte[] client_version;
-
- /**
- * Random bytes
- */
- final byte[] random = new byte[32];
-
- /**
- * Session id
- */
- final byte[] session_id;
-
- /**
- * Cipher suites supported by the client
- */
- final CipherSuite[] cipher_suites;
-
- /**
- * Compression methods supported by the client
- */
- final byte[] compression_methods;
-
- /**
- * Creates outbound message
- * @param sr
- * @param version
- * @param ses_id
- * @param cipher_suite
- */
- public ClientHello(SecureRandom sr, byte[] version, byte[] ses_id,
- CipherSuite[] cipher_suite) {
- client_version = version;
- long gmt_unix_time = System.currentTimeMillis()/1000;
- sr.nextBytes(random);
- random[0] = (byte) (gmt_unix_time & 0xFF000000 >>> 24);
- random[1] = (byte) (gmt_unix_time & 0xFF0000 >>> 16);
- random[2] = (byte) (gmt_unix_time & 0xFF00 >>> 8);
- random[3] = (byte) (gmt_unix_time & 0xFF);
- session_id = ses_id;
- this.cipher_suites = cipher_suite;
- compression_methods = new byte[] { 0 }; // CompressionMethod.null
- length = 38 + session_id.length + (this.cipher_suites.length << 1)
- + compression_methods.length;
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public ClientHello(HandshakeIODataStream in, int length) throws IOException {
- client_version = new byte[2];
- client_version[0] = (byte) in.readUint8();
- client_version[1] = (byte) in.readUint8();
- in.read(random, 0, 32);
- int size = in.read();
- session_id = new byte[size];
- in.read(session_id, 0, size);
- int l = in.readUint16();
- if ((l & 0x01) == 0x01) { // cipher suites length must be an even number
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect ClientHello");
- }
- size = l >> 1;
- cipher_suites = new CipherSuite[size];
- for (int i = 0; i < size; i++) {
- byte b0 = (byte) in.read();
- byte b1 = (byte) in.read();
- cipher_suites[i] = CipherSuite.getByCode(b0, b1);
- }
- size = in.read();
- compression_methods = new byte[size];
- in.read(compression_methods, 0, size);
- this.length = 38 + session_id.length + (cipher_suites.length << 1)
- + compression_methods.length;
- if (this.length > length) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect ClientHello");
- }
- // for forward compatibility, extra data is permitted;
- // must be ignored
- if (this.length < length) {
- in.skip(length - this.length);
- this.length = length;
- }
- }
- /**
- * Parse V2ClientHello
- * @param in
- * @throws IOException
- */
- public ClientHello(HandshakeIODataStream in) throws IOException {
- if (in.readUint8() != 1) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect V2ClientHello");
- }
- client_version = new byte[2];
- client_version[0] = (byte) in.readUint8();
- client_version[1] = (byte) in.readUint8();
- int cipher_spec_length = in.readUint16();
- if (in.readUint16() != 0) { // session_id_length
- // as client already knows the protocol known to a server it should
- // initiate the connection in that native protocol
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect V2ClientHello, cannot be used for resuming");
- }
- int challenge_length = in.readUint16();
- if (challenge_length < 16) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect V2ClientHello, short challenge data");
- }
- session_id = new byte[0];
- cipher_suites = new CipherSuite[cipher_spec_length/3];
- for (int i = 0; i < cipher_suites.length; i++) {
- byte b0 = (byte) in.read();
- byte b1 = (byte) in.read();
- byte b2 = (byte) in.read();
- cipher_suites[i] = CipherSuite.getByCode(b0, b1, b2);
- }
- compression_methods = new byte[] { 0 }; // CompressionMethod.null
-
- if (challenge_length < 32) {
- Arrays.fill(random, 0, 32 - challenge_length, (byte)0);
- System.arraycopy(in.read(challenge_length), 0, random, 32 - challenge_length, challenge_length);
- } else if (challenge_length == 32) {
- System.arraycopy(in.read(32), 0, random, 0, 32);
- } else {
- System.arraycopy(in.read(challenge_length), challenge_length - 32, random, 0, 32);
- }
- if (in.available() > 0) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect V2ClientHello, extra data");
- }
- this.length = 38 + session_id.length + (cipher_suites.length << 1)
- + compression_methods.length;
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- out.write(client_version);
- out.write(random);
- out.writeUint8(session_id.length);
- out.write(session_id);
- int size = cipher_suites.length << 1;
- out.writeUint16(size);
- for (int i = 0; i < cipher_suites.length; i++) {
- out.write(cipher_suites[i].toBytes());
- }
- out.writeUint8(compression_methods.length);
- for (int i = 0; i < compression_methods.length; i++) {
- out.write(compression_methods[i]);
- }
- }
-
- /**
- * Returns client random
- * @return client random
- */
- public byte[] getRandom() {
- return random;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CLIENT_HELLO;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientKeyExchange.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientKeyExchange.java
deleted file mode 100644
index af751c2..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientKeyExchange.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-
-import java.io.IOException;
-import java.math.BigInteger;
-
-/**
- * Represents client key exchange message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.7.
- * Client key exchange message</a>
- *
- */
-public class ClientKeyExchange extends Message {
-
- /**
- * Exchange keys
- */
- final byte[] exchange_keys;
-
- /**
- * Equals true if TLS1.0 protocol is used
- */
- boolean isTLS;
-
- /**
- * Equals true if key exchange algorithm is RSA
- */
- final boolean isRSA;
-
- /**
- * Creates outbound message
- * @param encrypted_pre_master_secret
- * @param isTLS
- */
- public ClientKeyExchange(byte[] encrypted_pre_master_secret, boolean isTLS) {
- this.exchange_keys = encrypted_pre_master_secret;
- length = this.exchange_keys.length;
- if (isTLS) {
- length += 2;
- }
- this.isTLS = isTLS;
- isRSA = true;
- }
-
- /**
- * Creates outbound message
- * @param dh_Yc
- */
- public ClientKeyExchange(BigInteger dh_Yc) {
- byte[] bb = dh_Yc.toByteArray();
- if (bb[0] == 0) {
- exchange_keys = new byte[bb.length-1];
- System.arraycopy(bb, 1, exchange_keys, 0, exchange_keys.length);
- } else {
- exchange_keys = bb;
- }
- length = exchange_keys.length +2;
- isRSA = false;
- }
-
- /**
- * Creates empty message
- *
- */
- public ClientKeyExchange() {
- exchange_keys = new byte[0];
- length = 0;
- isRSA = false;
- }
-
- /**
- * Creates inbound message
- * @param length
- * @param isTLS
- * @param isRSA
- * @throws IOException
- */
- public ClientKeyExchange(HandshakeIODataStream in, int length, boolean isTLS, boolean isRSA)
- throws IOException {
- this.isTLS = isTLS;
- this.isRSA = isRSA;
- if (length == 0) {
- this.length = 0;
- exchange_keys = new byte[0];
- } else {
- int size;
- if (isRSA && !isTLS) {// SSL3.0 RSA
- size = length;
- this.length = size;
- } else { // DH or TLSv1 RSA
- size = in.readUint16();
- this.length = 2 + size;
- }
- exchange_keys = new byte[size];
- in.read(exchange_keys, 0, size);
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect ClientKeyExchange");
- }
- }
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- if (exchange_keys.length != 0) {
- if (!isRSA || isTLS) {// DH or TLSv1 RSA
- out.writeUint16(exchange_keys.length);
- }
- out.write(exchange_keys);
- }
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.CLIENT_KEY_EXCHANGE;
- }
-
- /**
- * Returns true if the message is empty (in case of implicit DH Yc)
- * @return
- */
- public boolean isEmpty() {
- return (exchange_keys.length == 0);
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java
deleted file mode 100644
index 66e8d03..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ClientSessionContext.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import javax.net.ssl.SSLSession;
-
-/**
- * Caches client sessions. Indexes by host and port. Users are typically
- * looking to reuse any session for a given host and port. Users of the
- * standard API are forced to iterate over the sessions semi-linearly as
- * opposed to in constant time.
- */
-public class ClientSessionContext extends AbstractSessionContext {
-
- /*
- * We don't care about timeouts in the client implementation. Trying
- * to reuse an expired session and having to start a new one requires no
- * more effort than starting a new one, so you might as well try to reuse
- * one on the off chance it's still valid.
- */
-
- /** Sessions indexed by host and port in access order. */
- final Map<HostAndPort, SSLSession> sessions
- = new LinkedHashMap<HostAndPort, SSLSession>() {
- @Override
- protected boolean removeEldestEntry(
- Map.Entry<HostAndPort, SSLSession> eldest) {
- // Called while lock is held on sessions.
- boolean remove = maximumSize > 0 && size() > maximumSize;
- if (remove) {
- removeById(eldest.getValue());
- }
- return remove;
- }
- };
-
- /**
- * Sessions indexed by ID. Initialized on demand. Protected from concurrent
- * access by holding a lock on sessions.
- */
- Map<ByteArray, SSLSession> sessionsById;
-
- final SSLClientSessionCache persistentCache;
-
- public ClientSessionContext(int sslCtxNativePointer,
- SSLClientSessionCache persistentCache) {
- super(sslCtxNativePointer, 10, 0);
- this.persistentCache = persistentCache;
- }
-
- public final void setSessionTimeout(int seconds)
- throws IllegalArgumentException {
- if (seconds < 0) {
- throw new IllegalArgumentException("seconds < 0");
- }
- timeout = seconds;
- }
-
- Iterator<SSLSession> sessionIterator() {
- synchronized (sessions) {
- SSLSession[] array = sessions.values().toArray(
- new SSLSession[sessions.size()]);
- return Arrays.asList(array).iterator();
- }
- }
-
- void trimToSize() {
- synchronized (sessions) {
- int size = sessions.size();
- if (size > maximumSize) {
- int removals = size - maximumSize;
- Iterator<SSLSession> i = sessions.values().iterator();
- do {
- removeById(i.next());
- i.remove();
- } while (--removals > 0);
- }
- }
- }
-
- void removeById(SSLSession session) {
- if (sessionsById != null) {
- sessionsById.remove(new ByteArray(session.getId()));
- }
- }
-
- /**
- * {@inheritDoc}
- *
- * @see #getSession(String, int) for an implementation-specific but more
- * efficient approach
- */
- public SSLSession getSession(byte[] sessionId) {
- /*
- * This method is typically used in conjunction with getIds() to
- * iterate over the sessions linearly, so it doesn't make sense for
- * it to impact access order.
- *
- * It also doesn't load sessions from the persistent cache as doing
- * so would likely force every session to load.
- */
-
- ByteArray id = new ByteArray(sessionId);
- synchronized (sessions) {
- indexById();
- return sessionsById.get(id);
- }
- }
-
- /**
- * Ensures that the ID-based index is initialized.
- */
- private void indexById() {
- if (sessionsById == null) {
- sessionsById = new HashMap<ByteArray, SSLSession>();
- for (SSLSession session : sessions.values()) {
- sessionsById.put(new ByteArray(session.getId()), session);
- }
- }
- }
-
- /**
- * Adds the given session to the ID-based index if the index has already
- * been initialized.
- */
- private void indexById(byte[] id, SSLSession session) {
- if (sessionsById != null) {
- sessionsById.put(new ByteArray(id), session);
- }
- }
-
- /**
- * Finds a cached session for the given host name and port.
- *
- * @param host of server
- * @param port of server
- * @return cached session or null if none found
- */
- public SSLSession getSession(String host, int port) {
- synchronized (sessions) {
- SSLSession session = sessions.get(new HostAndPort(host, port));
- if (session != null) {
- return session;
- }
- }
-
- // Look in persistent cache.
- if (persistentCache != null) {
- byte[] data = persistentCache.getSessionData(host, port);
- if (data != null) {
- SSLSession session = toSession(data, host, port);
- if (session != null) {
- synchronized (sessions) {
- sessions.put(new HostAndPort(host, port), session);
- indexById(session.getId(), session);
- }
- return session;
- }
- }
- }
-
- return null;
- }
-
- @Override
- void putSession(SSLSession session) {
- byte[] id = session.getId();
- if (id.length == 0) {
- return;
- }
- HostAndPort key = new HostAndPort(session.getPeerHost(),
- session.getPeerPort());
- synchronized (sessions) {
- sessions.put(key, session);
- indexById(id, session);
- }
-
- // TODO: This in a background thread.
- if (persistentCache != null) {
- byte[] data = toBytes(session);
- if (data != null) {
- persistentCache.putSessionData(session, data);
- }
- }
- }
-
- static class HostAndPort {
- final String host;
- final int port;
-
- HostAndPort(String host, int port) {
- this.host = host;
- this.port = port;
- }
-
- @Override
- public int hashCode() {
- return host.hashCode() * 31 + port;
- }
-
- @Override
- @SuppressWarnings("EqualsWhichDoesntCheckParameterClass")
- public boolean equals(Object o) {
- HostAndPort other = (HostAndPort) o;
- return host.equals(other.host) && port == other.port;
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionState.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionState.java
deleted file mode 100644
index 49a7af9..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionState.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Logger;
-
-import javax.crypto.Cipher;
-
-/**
- * This abstract class is a base for Record Protocol operating environmet
- * of different SSL protocol versions.
- */
-public abstract class ConnectionState {
-
- /**
- * The cipher used for encode operations
- */
- protected Cipher encCipher;
-
- /**
- * The cipher used for decode operations
- */
- protected Cipher decCipher;
-
- /**
- * The cipher type
- */
- protected boolean is_block_cipher;
-
- /**
- * The size of MAC used under this connection state
- */
- protected int hash_size;
-
- /**
- * Write sequence number which is incremented after each
- * encrypt call
- */
- protected final byte[] write_seq_num = {0, 0, 0, 0, 0, 0, 0, 0};
-
- /**
- * Read sequence number which is incremented after each
- * decrypt call
- */
- protected final byte[] read_seq_num = {0, 0, 0, 0, 0, 0, 0, 0};
-
- protected Logger.Stream logger = Logger.getStream("conn_state");
-
- /**
- * Returns the minimal possible size of the
- * Generic[Stream|Generic]Cipher structure under this
- * connection state.
- */
- protected int getMinFragmentSize() {
- // block ciphers return value with padding included
- return encCipher.getOutputSize(1+hash_size); // 1 byte for data
- }
-
- /**
- * Returns the size of the Generic[Stream|Generic]Cipher structure
- * corresponding to the content data of specified size.
- */
- protected int getFragmentSize(int content_size) {
- return encCipher.getOutputSize(content_size+hash_size);
- }
-
- /**
- * Returns the minimal upper bound of the content size enclosed
- * into the Generic[Stream|Generic]Cipher structure of specified size.
- * For stream ciphers the returned value will be exact value.
- */
- protected int getContentSize(int generic_cipher_size) {
- //it does not take the padding of block ciphered structures
- //into account (so returned value can be greater than actual)
- return decCipher.getOutputSize(generic_cipher_size)-hash_size;
- }
-
- /**
- * Creates the GenericStreamCipher or GenericBlockCipher
- * data structure for specified data of specified type.
- * @param type - the ContentType of the provided data
- * @param fragment - the byte array containing the
- * data to be encrypted under the current connection state.
- */
- protected byte[] encrypt(byte type, byte[] fragment) {
- return encrypt(type, fragment, 0, fragment.length);
- }
-
- /**
- * Creates the GenericStreamCipher or GenericBlockCipher
- * data structure for specified data of specified type.
- * @param type - the ContentType of the provided data
- * @param fragment - the byte array containing the
- * data to be encrypted under the current connection state.
- * @param offset - the offset from which the data begins with.
- * @param len - the length of the data.
- */
- protected abstract byte[] encrypt
- (byte type, byte[] fragment, int offset, int len);
-
- /**
- * Retrieves the fragment of the Plaintext structure of
- * the specified type from the provided data.
- * @param type - the ContentType of the data to be decrypted.
- * @param fragment - the byte array containing the
- * data to be encrypted under the current connection state.
- */
- protected byte[] decrypt(byte type, byte[] fragment) {
- return decrypt(type, fragment, 0, fragment.length);
- }
-
- /**
- * Retrieves the fragment of the Plaintext structure of
- * the specified type from the provided data.
- * @param type - the ContentType of the data to be decrypted.
- * @param fragment - the byte array containing the
- * data to be encrypted under the current connection state.
- * @param offset - the offset from which the data begins with.
- * @param len - the length of the data.
- */
- protected abstract byte[] decrypt
- (byte type, byte[] fragment, int offset, int len);
-
- /**
- * Increments the sequence number.
- */
- protected static void incSequenceNumber(byte[] seq_num) {
- int octet = 7;
- while (octet >= 0) {
- seq_num[octet] ++;
- if (seq_num[octet] == 0) {
- // characteristic overflow, so
- // carrying a number in adding
- octet --;
- } else {
- return;
- }
- }
- }
-
- /**
- * Shutdownes the protocol. It will be impossiblke to use the instance
- * after the calling of this method.
- */
- protected void shutdown() {
- encCipher = null;
- decCipher = null;
- for (int i=0; i<write_seq_num.length; i++) {
- write_seq_num[i] = 0;
- read_seq_num[i] = 0;
- }
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateSSLv3.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateSSLv3.java
deleted file mode 100644
index 07bd340..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateSSLv3.java
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
-import java.util.Arrays;
-import javax.crypto.Cipher;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-import javax.net.ssl.SSLProtocolException;
-
-/**
- * This class encapsulates the operating environment of the SSL v3
- * (http://wp.netscape.com/eng/ssl3) Record Protocol and provides
- * relating encryption/decryption functionality.
- * The work functionality is based on the security
- * parameters negotiated during the handshake.
- */
-public class ConnectionStateSSLv3 extends ConnectionState {
-
- // digest to create and check the message integrity info
- private final MessageDigest messageDigest;
- private final byte[] mac_write_secret;
- private final byte[] mac_read_secret;
-
- // paddings
- private final byte[] pad_1;
- private final byte[] pad_2;
- // array will hold the part of the MAC material:
- // length of 3 == 1(SSLCompressed.type) + 2(SSLCompressed.length)
- // (more on SSLv3 MAC computation and payload protection see
- // SSL v3 specification, p. 5.2.3)
- private final byte[] mac_material_part = new byte[3];
-
- /**
- * Creates the instance of SSL v3 Connection State. All of the
- * security parameters are provided by session object.
- * @param session: the sessin object which incapsulates
- * all of the security parameters established by handshake protocol.
- * The key calculation for the state is done according
- * to the SSL v3 Protocol specification.
- * (http://www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt)
- */
- protected ConnectionStateSSLv3(SSLSessionImpl session) {
- try {
- CipherSuite cipherSuite = session.cipherSuite;
-
- boolean is_exportabe = cipherSuite.isExportable();
- hash_size = cipherSuite.getMACLength();
- int key_size = (is_exportabe)
- ? cipherSuite.keyMaterial
- : cipherSuite.expandedKeyMaterial;
- int iv_size = cipherSuite.getBlockSize();
-
- String algName = cipherSuite.getBulkEncryptionAlgorithm();
- String hashName = cipherSuite.getHashName();
- if (logger != null) {
- logger.println("ConnectionStateSSLv3.create:");
- logger.println(" cipher suite name: "
- + session.getCipherSuite());
- logger.println(" encryption alg name: " + algName);
- logger.println(" hash alg name: " + hashName);
- logger.println(" hash size: " + hash_size);
- logger.println(" block size: " + iv_size);
- logger.println(" IV size (== block size):" + iv_size);
- logger.println(" key size: " + key_size);
- }
-
- byte[] clientRandom = session.clientRandom;
- byte[] serverRandom = session.serverRandom;
- // so we need PRF value of size of
- // 2*hash_size + 2*key_size + 2*iv_size
- byte[] key_block = new byte[2*hash_size + 2*key_size + 2*iv_size];
- byte[] seed = new byte[clientRandom.length + serverRandom.length];
- System.arraycopy(serverRandom, 0, seed, 0, serverRandom.length);
- System.arraycopy(clientRandom, 0, seed, serverRandom.length,
- clientRandom.length);
-
- PRF.computePRF_SSLv3(key_block, session.master_secret, seed);
-
- byte[] client_mac_secret = new byte[hash_size];
- byte[] server_mac_secret = new byte[hash_size];
- byte[] client_key = new byte[key_size];
- byte[] server_key = new byte[key_size];
-
- boolean is_client = !session.isServer;
-
- is_block_cipher = (iv_size > 0);
-
- System.arraycopy(key_block, 0, client_mac_secret, 0, hash_size);
- System.arraycopy(key_block, hash_size,
- server_mac_secret, 0, hash_size);
- System.arraycopy(key_block, 2*hash_size, client_key, 0, key_size);
- System.arraycopy(key_block, 2*hash_size+key_size,
- server_key, 0, key_size);
-
- IvParameterSpec clientIV = null;
- IvParameterSpec serverIV = null;
-
- if (is_exportabe) {
- if (logger != null) {
- logger.println("ConnectionStateSSLv3: is_exportable");
- }
-
- MessageDigest md5 = MessageDigest.getInstance("MD5");
- md5.update(client_key);
- md5.update(clientRandom);
- md5.update(serverRandom);
- client_key = md5.digest();
-
- md5.update(server_key);
- md5.update(serverRandom);
- md5.update(clientRandom);
- server_key = md5.digest();
-
- key_size = cipherSuite.expandedKeyMaterial;
-
- if (is_block_cipher) {
- md5.update(clientRandom);
- md5.update(serverRandom);
- clientIV = new IvParameterSpec(md5.digest(), 0, iv_size);
- md5.update(serverRandom);
- md5.update(clientRandom);
- serverIV = new IvParameterSpec(md5.digest(), 0, iv_size);
- }
- } else if (is_block_cipher) {
- clientIV = new IvParameterSpec(key_block,
- 2*hash_size+2*key_size, iv_size);
- serverIV = new IvParameterSpec(key_block,
- 2*hash_size+2*key_size+iv_size, iv_size);
- }
-
- if (logger != null) {
- logger.println("is exportable: "+is_exportabe);
- logger.println("master_secret");
- logger.print(session.master_secret);
- logger.println("client_random");
- logger.print(clientRandom);
- logger.println("server_random");
- logger.print(serverRandom);
- //logger.println("key_block");
- //logger.print(key_block);
- logger.println("client_mac_secret");
- logger.print(client_mac_secret);
- logger.println("server_mac_secret");
- logger.print(server_mac_secret);
- logger.println("client_key");
- logger.print(client_key, 0, key_size);
- logger.println("server_key");
- logger.print(server_key, 0, key_size);
- if (clientIV != null) {
- logger.println("client_iv");
- logger.print(clientIV.getIV());
- logger.println("server_iv");
- logger.print(serverIV.getIV());
- } else {
- logger.println("no IV.");
- }
- }
- encCipher = Cipher.getInstance(algName);
- decCipher = Cipher.getInstance(algName);
- messageDigest = MessageDigest.getInstance(hashName);
- if (is_client) { // client side
- encCipher.init(Cipher.ENCRYPT_MODE,
- new SecretKeySpec(client_key, 0, key_size, algName),
- clientIV);
- decCipher.init(Cipher.DECRYPT_MODE,
- new SecretKeySpec(server_key, 0, key_size, algName),
- serverIV);
- mac_write_secret = client_mac_secret;
- mac_read_secret = server_mac_secret;
- } else { // server side
- encCipher.init(Cipher.ENCRYPT_MODE,
- new SecretKeySpec(server_key, 0, key_size, algName),
- serverIV);
- decCipher.init(Cipher.DECRYPT_MODE,
- new SecretKeySpec(client_key, 0, key_size, algName),
- clientIV);
- mac_write_secret = server_mac_secret;
- mac_read_secret = client_mac_secret;
- }
- if (hashName.equals("MD5")) {
- pad_1 = SSLv3Constants.MD5pad1;
- pad_2 = SSLv3Constants.MD5pad2;
- } else {
- pad_1 = SSLv3Constants.SHApad1;
- pad_2 = SSLv3Constants.SHApad2;
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException(
- "Error during computation of security parameters"));
- }
- }
-
- /**
- * Creates the GenericStreamCipher or GenericBlockCipher
- * data structure for specified data of specified type.
- * @throws AlertException if alert was occurred.
- */
- @Override
- protected byte[] encrypt(byte type, byte[] fragment, int offset, int len) {
- try {
- int content_mac_length = len + hash_size;
- int padding_length = is_block_cipher
- ? padding_length =
- ((8 - (++content_mac_length & 0x07)) & 0x07)
- : 0;
- byte[] res = new byte[content_mac_length + padding_length];
- System.arraycopy(fragment, offset, res, 0, len);
-
- mac_material_part[0] = type;
- mac_material_part[1] = (byte) ((0x00FF00 & len) >> 8);
- mac_material_part[2] = (byte) (0x0000FF & len);
-
- messageDigest.update(mac_write_secret);
- messageDigest.update(pad_1);
- messageDigest.update(write_seq_num);
- messageDigest.update(mac_material_part);
- messageDigest.update(fragment, offset, len);
- byte[] digest = messageDigest.digest();
- messageDigest.update(mac_write_secret);
- messageDigest.update(pad_2);
- messageDigest.update(digest);
- digest = messageDigest.digest();
- System.arraycopy(digest, 0, res, len, hash_size);
-
- //if (logger != null) {
- // logger.println("MAC Material:");
- // logger.print(write_seq_num);
- // logger.print(mac_material_header);
- // logger.print(fragment, offset, len);
- //}
-
- if (is_block_cipher) {
- // do padding:
- Arrays.fill(res, content_mac_length-1,
- res.length, (byte) (padding_length));
- }
- if (logger != null) {
- logger.println("SSLRecordProtocol.encrypt: "
- + (is_block_cipher
- ? "GenericBlockCipher with padding["
- +padding_length+"]:"
- : "GenericStreamCipher:"));
- logger.print(res);
- }
- byte[] rez = new byte[encCipher.getOutputSize(res.length)];
- encCipher.update(res, 0, res.length, rez);
- incSequenceNumber(write_seq_num);
- return rez;
- } catch (GeneralSecurityException e) {
- e.printStackTrace();
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException("Error during the encryption"));
- }
- }
-
- /**
- * Retrieves the fragment of the Plaintext structure of
- * the specified type from the provided data.
- * @throws AlertException if alert was occured.
- */
- @Override
- protected byte[] decrypt(byte type, byte[] fragment,
- int offset, int len) {
- // plain data of the Generic[Stream|Block]Cipher structure
- byte[] data = decCipher.update(fragment, offset, len);
- // the 'content' part of the structure
- byte[] content;
- if (is_block_cipher) {
- // check padding
- int padding_length = data[data.length-1];
- for (int i=0; i<padding_length; i++) {
- if (data[data.length-2-i] != padding_length) {
- throw new AlertException(
- AlertProtocol.DECRYPTION_FAILED,
- new SSLProtocolException(
- "Received message has bad padding"));
- }
- }
- content = new byte[data.length - hash_size - padding_length - 1];
- } else {
- content = new byte[data.length - hash_size];
- }
-
- byte[] mac_value;
-
- mac_material_part[0] = type;
- mac_material_part[1] = (byte) ((0x00FF00 & content.length) >> 8);
- mac_material_part[2] = (byte) (0x0000FF & content.length);
-
- messageDigest.update(mac_read_secret);
- messageDigest.update(pad_1);
- messageDigest.update(read_seq_num);
- messageDigest.update(mac_material_part);
- messageDigest.update(data, 0, content.length);
- mac_value = messageDigest.digest();
- messageDigest.update(mac_read_secret);
- messageDigest.update(pad_2);
- messageDigest.update(mac_value);
- mac_value = messageDigest.digest();
-
- if (logger != null) {
- logger.println("Decrypted:");
- logger.print(data);
- //logger.println("MAC Material:");
- //logger.print(read_seq_num);
- //logger.print(mac_material_header);
- //logger.print(data, 0, content.length);
- logger.println("Expected mac value:");
- logger.print(mac_value);
- }
- // checking the mac value
- for (int i=0; i<hash_size; i++) {
- if (mac_value[i] != data[i+content.length]) {
- throw new AlertException(AlertProtocol.BAD_RECORD_MAC,
- new SSLProtocolException("Bad record MAC"));
- }
- }
- System.arraycopy(data, 0, content, 0, content.length);
- incSequenceNumber(read_seq_num);
- return content;
- }
-
- /**
- * Shutdown the protocol. It will be impossible to use the instance
- * after the calling of this method.
- */
- @Override
- protected void shutdown() {
- Arrays.fill(mac_write_secret, (byte) 0);
- Arrays.fill(mac_read_secret, (byte) 0);
- super.shutdown();
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateTLS.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateTLS.java
deleted file mode 100644
index 949e655..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ConnectionStateTLS.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.SSLSessionImpl;
-import org.apache.harmony.xnet.provider.jsse.PRF;
-import org.apache.harmony.xnet.provider.jsse.ConnectionState;
-
-import java.security.GeneralSecurityException;
-import java.util.Arrays;
-import javax.crypto.Cipher;
-import javax.crypto.Mac;
-import javax.crypto.spec.IvParameterSpec;
-import javax.crypto.spec.SecretKeySpec;
-import javax.net.ssl.SSLProtocolException;
-
-/**
- * This class encapsulates the operating environment of the TLS v1
- * (http://www.ietf.org/rfc/rfc2246.txt) Record Protocol and provides
- * relating encryption/decryption functionality.
- * The work functionality is based on the security
- * parameters negotiated during the handshake.
- */
-public class ConnectionStateTLS extends ConnectionState {
-
- // Pre-calculated prf label values:
- // "key expansion".getBytes()
- private static byte[] KEY_EXPANSION_LABEL = {
- (byte) 0x6B, (byte) 0x65, (byte) 0x79, (byte) 0x20, (byte) 0x65,
- (byte) 0x78, (byte) 0x70, (byte) 0x61, (byte) 0x6E, (byte) 0x73,
- (byte) 0x69, (byte) 0x6F, (byte) 0x6E };
-
- // "client write key".getBytes()
- private static byte[] CLIENT_WRITE_KEY_LABEL = {
- (byte) 0x63, (byte) 0x6C, (byte) 0x69, (byte) 0x65, (byte) 0x6E,
- (byte) 0x74, (byte) 0x20, (byte) 0x77, (byte) 0x72, (byte) 0x69,
- (byte) 0x74, (byte) 0x65, (byte) 0x20, (byte) 0x6B, (byte) 0x65,
- (byte) 0x79 };
-
- // "server write key".getBytes()
- private static byte[] SERVER_WRITE_KEY_LABEL = {
- (byte) 0x73, (byte) 0x65, (byte) 0x72, (byte) 0x76, (byte) 0x65,
- (byte) 0x72, (byte) 0x20, (byte) 0x77, (byte) 0x72, (byte) 0x69,
- (byte) 0x74, (byte) 0x65, (byte) 0x20, (byte) 0x6B, (byte) 0x65,
- (byte) 0x79 };
-
- // "IV block".getBytes()
- private static byte[] IV_BLOCK_LABEL = {
- (byte) 0x49, (byte) 0x56, (byte) 0x20, (byte) 0x62, (byte) 0x6C,
- (byte) 0x6F, (byte) 0x63, (byte) 0x6B };
-
- // MACs to create and check the message integrity info
- private final Mac encMac;
- private final Mac decMac;
-
- // Once created permanently used array:
- // is used to create the header of the MAC material value:
- // 5 == 1(TLSCompressed.type) + 2(TLSCompressed.version) +
- // 2(TLSCompressed.length)
- private final byte[] mac_material_header = new byte[] {0, 3, 1, 0, 0};
-
- /**
- * Creates the instance of TLS v1 Connection State. All of the
- * security parameters are provided by session object.
- * @param session: the sessin object which incapsulates
- * all of the security parameters established by handshake protocol.
- * The key calculation for the state is done according
- * to the TLS v 1.0 Protocol specification.
- * (http://www.ietf.org/rfc/rfc2246.txt)
- */
- protected ConnectionStateTLS(SSLSessionImpl session) {
- try {
- CipherSuite cipherSuite = session.cipherSuite;
-
- hash_size = cipherSuite.getMACLength();
- boolean is_exportabe = cipherSuite.isExportable();
- int key_size = (is_exportabe)
- ? cipherSuite.keyMaterial
- : cipherSuite.expandedKeyMaterial;
- int iv_size = cipherSuite.getBlockSize();
-
- String algName = cipherSuite.getBulkEncryptionAlgorithm();
- String macName = cipherSuite.getHmacName();
- if (logger != null) {
- logger.println("ConnectionStateTLS.create:");
- logger.println(" cipher suite name: "
- + cipherSuite.getName());
- logger.println(" encryption alg name: " + algName);
- logger.println(" mac alg name: " + macName);
- logger.println(" hash size: " + hash_size);
- logger.println(" block size: " + iv_size);
- logger.println(" IV size (== block size):" + iv_size);
- logger.println(" key size: " + key_size);
- }
-
- byte[] clientRandom = session.clientRandom;
- byte[] serverRandom = session.serverRandom;
- // so we need PRF value of size of
- // 2*hash_size + 2*key_size + 2*iv_size
- byte[] key_block = new byte[2*hash_size + 2*key_size + 2*iv_size];
- byte[] seed = new byte[clientRandom.length + serverRandom.length];
- System.arraycopy(serverRandom, 0, seed, 0, serverRandom.length);
- System.arraycopy(clientRandom, 0, seed, serverRandom.length,
- clientRandom.length);
-
- PRF.computePRF(key_block, session.master_secret,
- KEY_EXPANSION_LABEL, seed);
-
- byte[] client_mac_secret = new byte[hash_size];
- byte[] server_mac_secret = new byte[hash_size];
- byte[] client_key = new byte[key_size];
- byte[] server_key = new byte[key_size];
-
- boolean is_client = !session.isServer;
-
- is_block_cipher = (iv_size > 0);
- // do not count, as block_size is always 8
- // block_size = iv_size;
-
- System.arraycopy(key_block, 0, client_mac_secret, 0, hash_size);
- System.arraycopy(key_block, hash_size,
- server_mac_secret, 0, hash_size);
- System.arraycopy(key_block, 2*hash_size, client_key, 0, key_size);
- System.arraycopy(key_block, 2*hash_size+key_size,
- server_key, 0, key_size);
-
- IvParameterSpec clientIV = null;
- IvParameterSpec serverIV = null;
-
- if (is_exportabe) {
- System.arraycopy(clientRandom, 0,
- seed, 0, clientRandom.length);
- System.arraycopy(serverRandom, 0,
- seed, clientRandom.length, serverRandom.length);
- byte[] final_client_key =
- new byte[cipherSuite.expandedKeyMaterial];
- byte[] final_server_key =
- new byte[cipherSuite.expandedKeyMaterial];
- PRF.computePRF(final_client_key, client_key,
- CLIENT_WRITE_KEY_LABEL, seed);
- PRF.computePRF(final_server_key, server_key,
- SERVER_WRITE_KEY_LABEL, seed);
- client_key = final_client_key;
- server_key = final_server_key;
- if (is_block_cipher) {
- byte[] iv_block = new byte[2*iv_size];
- PRF.computePRF(iv_block, null, IV_BLOCK_LABEL, seed);
- clientIV = new IvParameterSpec(iv_block, 0, iv_size);
- serverIV = new IvParameterSpec(iv_block, iv_size, iv_size);
- }
- } else if (is_block_cipher) {
- clientIV = new IvParameterSpec(key_block,
- 2*(hash_size+key_size), iv_size);
- serverIV = new IvParameterSpec(key_block,
- 2*(hash_size+key_size)+iv_size, iv_size);
- }
-
- if (logger != null) {
- logger.println("is exportable: "+is_exportabe);
- logger.println("master_secret");
- logger.print(session.master_secret);
- logger.println("client_random");
- logger.print(clientRandom);
- logger.println("server_random");
- logger.print(serverRandom);
- //logger.println("key_block");
- //logger.print(key_block);
- logger.println("client_mac_secret");
- logger.print(client_mac_secret);
- logger.println("server_mac_secret");
- logger.print(server_mac_secret);
- logger.println("client_key");
- logger.print(client_key);
- logger.println("server_key");
- logger.print(server_key);
- if (clientIV == null) {
- logger.println("no IV.");
- } else {
- logger.println("client_iv");
- logger.print(clientIV.getIV());
- logger.println("server_iv");
- logger.print(serverIV.getIV());
- }
- }
-
- encCipher = Cipher.getInstance(algName);
- decCipher = Cipher.getInstance(algName);
- encMac = Mac.getInstance(macName);
- decMac = Mac.getInstance(macName);
-
- if (is_client) { // client side
- encCipher.init(Cipher.ENCRYPT_MODE,
- new SecretKeySpec(client_key, algName), clientIV);
- decCipher.init(Cipher.DECRYPT_MODE,
- new SecretKeySpec(server_key, algName), serverIV);
- encMac.init(new SecretKeySpec(client_mac_secret, macName));
- decMac.init(new SecretKeySpec(server_mac_secret, macName));
- } else { // server side
- encCipher.init(Cipher.ENCRYPT_MODE,
- new SecretKeySpec(server_key, algName), serverIV);
- decCipher.init(Cipher.DECRYPT_MODE,
- new SecretKeySpec(client_key, algName), clientIV);
- encMac.init(new SecretKeySpec(server_mac_secret, macName));
- decMac.init(new SecretKeySpec(client_mac_secret, macName));
- }
- } catch (Exception e) {
- e.printStackTrace();
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException(
- "Error during computation of security parameters"));
- }
- }
-
- /**
- * Creates the GenericStreamCipher or GenericBlockCipher
- * data structure for specified data of specified type.
- * @throws AlertException if alert was occurred.
- */
- @Override
- protected byte[] encrypt(byte type, byte[] fragment, int offset, int len) {
- try {
- int content_mac_length = len + hash_size;
- int padding_length = is_block_cipher
- ? ((8 - (++content_mac_length & 0x07)) & 0x07)
- : 0;
- byte[] res = new byte[content_mac_length + padding_length];
- System.arraycopy(fragment, offset, res, 0, len);
-
- mac_material_header[0] = type;
- mac_material_header[3] = (byte) ((0x00FF00 & len) >> 8);
- mac_material_header[4] = (byte) (0x0000FF & len);
-
- encMac.update(write_seq_num);
- encMac.update(mac_material_header);
- encMac.update(fragment, offset, len);
- encMac.doFinal(res, len);
-
- //if (logger != null) {
- // logger.println("MAC Material:");
- // logger.print(write_seq_num);
- // logger.print(mac_material_header);
- // logger.print(fragment, offset, len);
- //}
-
- if (is_block_cipher) {
- // do padding:
- Arrays.fill(res, content_mac_length-1,
- res.length, (byte) (padding_length));
- }
- if (logger != null) {
- logger.println("SSLRecordProtocol.do_encryption: Generic"
- + (is_block_cipher
- ? "BlockCipher with padding["+padding_length+"]:"
- : "StreamCipher:"));
- logger.print(res);
- }
- byte[] rez = new byte[encCipher.getOutputSize(res.length)];
- // We should not call just doFinal because it reinitialize
- // the cipher, but as says rfc 2246:
- // "For stream ciphers that do not use a synchronization
- // vector (such as RC4), the stream cipher state from the end
- // of one record is simply used on the subsequent packet."
- // and for block ciphers:
- // "The IV for subsequent records is the last ciphertext block from
- // the previous record."
- // i.e. we should keep the cipher state.
- encCipher.update(res, 0, res.length, rez);
- incSequenceNumber(write_seq_num);
- return rez;
- } catch (GeneralSecurityException e) {
- e.printStackTrace();
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException("Error during the encryption"));
- }
- }
-
- /**
- * Retrieves the fragment of the Plaintext structure of
- * the specified type from the provided data representing
- * the Generic[Stream|Block]Cipher structure.
- * @throws AlertException if alert was occurred.
- */
- @Override
- protected byte[] decrypt(byte type, byte[] fragment,
- int offset, int len) {
- // plain data of the Generic[Stream|Block]Cipher structure
- byte[] data = decCipher.update(fragment, offset, len);
- // the 'content' part of the structure
- byte[] content;
- if (is_block_cipher) {
- // check padding
- int padding_length = data[data.length-1];
- for (int i=0; i<padding_length; i++) {
- if (data[data.length-2-i] != padding_length) {
- throw new AlertException(
- AlertProtocol.DECRYPTION_FAILED,
- new SSLProtocolException(
- "Received message has bad padding"));
- }
- }
- content = new byte[data.length - hash_size - padding_length - 1];
- } else {
- content = new byte[data.length - hash_size];
- }
-
- mac_material_header[0] = type;
- mac_material_header[3] = (byte) ((0x00FF00 & content.length) >> 8);
- mac_material_header[4] = (byte) (0x0000FF & content.length);
-
- decMac.update(read_seq_num);
- decMac.update(mac_material_header);
- decMac.update(data, 0, content.length); // mac.update(fragment);
- byte[] mac_value = decMac.doFinal();
- if (logger != null) {
- logger.println("Decrypted:");
- logger.print(data);
- //logger.println("MAC Material:");
- //logger.print(read_seq_num);
- //logger.print(mac_material_header);
- //logger.print(data, 0, content.length);
- logger.println("Expected mac value:");
- logger.print(mac_value);
- }
- // checking the mac value
- for (int i=0; i<hash_size; i++) {
- if (mac_value[i] != data[i+content.length]) {
- throw new AlertException(AlertProtocol.BAD_RECORD_MAC,
- new SSLProtocolException("Bad record MAC"));
- }
- }
- System.arraycopy(data, 0, content, 0, content.length);
- incSequenceNumber(read_seq_num);
- return content;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ContentType.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ContentType.java
deleted file mode 100644
index 69704f5..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ContentType.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- * This class incapsulates the constants determining the
- * types of SSL/TLS record's content data.
- * Constant values are taken according to the TLS v1 specification
- * (http://www.ietf.org/rfc/rfc2246.txt).
- */
-public class ContentType {
-
- /**
- * Identifies change cipher spec message
- */
- protected static final byte CHANGE_CIPHER_SPEC = 20;
-
- /**
- * Identifies alert message
- */
- protected static final byte ALERT = 21;
-
- /**
- * Identifies handshake message
- */
- protected static final byte HANDSHAKE = 22;
-
- /**
- * Identifies application data message
- */
- protected static final byte APPLICATION_DATA = 23;
-
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DHParameters.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DHParameters.java
deleted file mode 100644
index 441fc5f..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DHParameters.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- * This class contains well-known primes
- */
-public class DHParameters {
-
- // Well-known 512 bit prime
- // http://news.hping.org/sci.crypt.archive/2370.html
- private static byte[] prime512 = new byte[] { (byte) 0xF5, (byte) 0x2A, (byte) 0xFF,
- (byte) 0x3C, (byte) 0xE1, (byte) 0xB1, (byte) 0x29, (byte) 0x40,
- (byte) 0x18, (byte) 0x11, (byte) 0x8D, (byte) 0x7C, (byte) 0x84,
- (byte) 0xA7, (byte) 0x0A, (byte) 0x72, (byte) 0xD6, (byte) 0x86,
- (byte) 0xC4, (byte) 0x03, (byte) 0x19, (byte) 0xC8, (byte) 0x07,
- (byte) 0x29, (byte) 0x7A, (byte) 0xCA, (byte) 0x95, (byte) 0x0C,
- (byte) 0xD9, (byte) 0x96, (byte) 0x9F, (byte) 0xAB, (byte) 0xD0,
- (byte) 0x0A, (byte) 0x50, (byte) 0x9B, (byte) 0x02, (byte) 0x46,
- (byte) 0xD3, (byte) 0x08, (byte) 0x3D, (byte) 0x66, (byte) 0xA4,
- (byte) 0x5D, (byte) 0x41, (byte) 0x9F, (byte) 0x9C, (byte) 0x7C,
- (byte) 0xBD, (byte) 0x89, (byte) 0x4B, (byte) 0x22, (byte) 0x19,
- (byte) 0x26, (byte) 0xBA, (byte) 0xAB, (byte) 0xA2, (byte) 0x5E,
- (byte) 0xC3, (byte) 0x55, (byte) 0xE9, (byte) 0x2A, (byte) 0x05,
- (byte) 0x5F };
-
- // Well-Known Group 1: A 768 bit prime rfc 2539
- // (http://www.ietf.org/rfc/rfc2539.txt?number=2539)
- private static byte[] primeGroup1 = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC9,
- (byte) 0x0F, (byte) 0xDA, (byte) 0xA2, (byte) 0x21, (byte) 0x68,
- (byte) 0xC2, (byte) 0x34, (byte) 0xC4, (byte) 0xC6, (byte) 0x62,
- (byte) 0x8B, (byte) 0x80, (byte) 0xDC, (byte) 0x1C, (byte) 0xD1,
- (byte) 0x29, (byte) 0x02, (byte) 0x4E, (byte) 0x08, (byte) 0x8A,
- (byte) 0x67, (byte) 0xCC, (byte) 0x74, (byte) 0x02, (byte) 0x0B,
- (byte) 0xBE, (byte) 0xA6, (byte) 0x3B, (byte) 0x13, (byte) 0x9B,
- (byte) 0x22, (byte) 0x51, (byte) 0x4A, (byte) 0x08, (byte) 0x79,
- (byte) 0x8E, (byte) 0x34, (byte) 0x04, (byte) 0xDD, (byte) 0xEF,
- (byte) 0x95, (byte) 0x19, (byte) 0xB3, (byte) 0xCD, (byte) 0x3A,
- (byte) 0x43, (byte) 0x1B, (byte) 0x30, (byte) 0x2B, (byte) 0x0A,
- (byte) 0x6D, (byte) 0xF2, (byte) 0x5F, (byte) 0x14, (byte) 0x37,
- (byte) 0x4F, (byte) 0xE1, (byte) 0x35, (byte) 0x6D, (byte) 0x6D,
- (byte) 0x51, (byte) 0xC2, (byte) 0x45, (byte) 0xE4, (byte) 0x85,
- (byte) 0xB5, (byte) 0x76, (byte) 0x62, (byte) 0x5E, (byte) 0x7E,
- (byte) 0xC6, (byte) 0xF4, (byte) 0x4C, (byte) 0x42, (byte) 0xE9,
- (byte) 0xA6, (byte) 0x3A, (byte) 0x36, (byte) 0x20, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF };
-
- // Well-Known Group 2: A 1024 bit prime rfc 2539
- // (http://www.ietf.org/rfc/rfc2539.txt?number=2539)
- private static byte[] primeGroup2 = { (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xC9,
- (byte) 0x0F, (byte) 0xDA, (byte) 0xA2, (byte) 0x21, (byte) 0x68,
- (byte) 0xC2, (byte) 0x34, (byte) 0xC4, (byte) 0xC6, (byte) 0x62,
- (byte) 0x8B, (byte) 0x80, (byte) 0xDC, (byte) 0x1C, (byte) 0xD1,
- (byte) 0x29, (byte) 0x02, (byte) 0x4E, (byte) 0x08, (byte) 0x8A,
- (byte) 0x67, (byte) 0xCC, (byte) 0x74, (byte) 0x02, (byte) 0x0B,
- (byte) 0xBE, (byte) 0xA6, (byte) 0x3B, (byte) 0x13, (byte) 0x9B,
- (byte) 0x22, (byte) 0x51, (byte) 0x4A, (byte) 0x08, (byte) 0x79,
- (byte) 0x8E, (byte) 0x34, (byte) 0x04, (byte) 0xDD, (byte) 0xEF,
- (byte) 0x95, (byte) 0x19, (byte) 0xB3, (byte) 0xCD, (byte) 0x3A,
- (byte) 0x43, (byte) 0x1B, (byte) 0x30, (byte) 0x2B, (byte) 0x0A,
- (byte) 0x6D, (byte) 0xF2, (byte) 0x5F, (byte) 0x14, (byte) 0x37,
- (byte) 0x4F, (byte) 0xE1, (byte) 0x35, (byte) 0x6D, (byte) 0x6D,
- (byte) 0x51, (byte) 0xC2, (byte) 0x45, (byte) 0xE4, (byte) 0x85,
- (byte) 0xB5, (byte) 0x76, (byte) 0x62, (byte) 0x5E, (byte) 0x7E,
- (byte) 0xC6, (byte) 0xF4, (byte) 0x4C, (byte) 0x42, (byte) 0xE9,
- (byte) 0xA6, (byte) 0x37, (byte) 0xED, (byte) 0x6B, (byte) 0x0B,
- (byte) 0xFF, (byte) 0x5C, (byte) 0xB6, (byte) 0xF4, (byte) 0x06,
- (byte) 0xB7, (byte) 0xED, (byte) 0xEE, (byte) 0x38, (byte) 0x6B,
- (byte) 0xFB, (byte) 0x5A, (byte) 0x89, (byte) 0x9F, (byte) 0xA5,
- (byte) 0xAE, (byte) 0x9F, (byte) 0x24, (byte) 0x11, (byte) 0x7C,
- (byte) 0x4B, (byte) 0x1F, (byte) 0xE6, (byte) 0x49, (byte) 0x28,
- (byte) 0x66, (byte) 0x51, (byte) 0xEC, (byte) 0xE6, (byte) 0x53,
- (byte) 0x81, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF,
- (byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF
- };
-
- private static byte[] prime;
-
- static {
-//TODO set prime depand on some system or security property
- prime = prime512;
- }
-
- /**
- * Returns prime bytes
- * @return
- */
- public static byte[] getPrime() {
- return prime;
- }
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DataStream.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DataStream.java
deleted file mode 100644
index ffc8612..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DataStream.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- * This interface represents the ability of the
- * classes to provide the chunks of data.
- */
-public interface DataStream {
-
- /**
- * Checks if there is data to be read.
- * @return true if there is the input data in the stream,
- * false otherwise
- */
- public boolean hasData();
-
- /**
- * Retrieves the data of specified length from the stream.
- * If the data size in the stream is less than specified length,
- * method returns all the data contained in the stream.
- * @return byte array containing the demanded data.
- */
- public byte[] getData(int length);
-
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java
deleted file mode 100644
index 3b2e103..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DelegatedTask.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.HandshakeProtocol;
-
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.PrivilegedActionException;
-import java.security.PrivilegedExceptionAction;
-
-/**
- * Delegated Runnable task for SSLEngine
- */
-public class DelegatedTask implements Runnable {
-
- private final HandshakeProtocol handshaker;
- private final PrivilegedExceptionAction<Void> action;
- private final AccessControlContext context;
-
- /**
- * Creates DelegatedTask
- * @param action
- * @param handshaker
- * @param context
- */
- public DelegatedTask(PrivilegedExceptionAction<Void> action, HandshakeProtocol handshaker, AccessControlContext context) {
- this.action = action;
- this.handshaker = handshaker;
- this.context = context;
- }
-
- /**
- * Executes DelegatedTask
- */
- public void run() {
- synchronized (handshaker) {
- try {
- AccessController.doPrivileged(action, context);
- } catch (PrivilegedActionException e) {
- // pass exception to HandshakeProtocol
- handshaker.delegatedTaskErr = e.getException();
- } catch (RuntimeException e) {
- // pass exception to HandshakeProtocol
- handshaker.delegatedTaskErr = e;
- }
- }
-
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DigitalSignature.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DigitalSignature.java
deleted file mode 100644
index a0f18b4..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/DigitalSignature.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.DigestException;
-import java.security.InvalidKeyException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.cert.Certificate;
-import java.util.Arrays;
-
-import javax.crypto.BadPaddingException;
-import javax.crypto.Cipher;
-import javax.crypto.IllegalBlockSizeException;
-import javax.crypto.NoSuchPaddingException;
-import javax.net.ssl.SSLException;
-
-/**
- * This class represents Signature type, as described in TLS v 1.0 Protocol
- * specification, 7.4.3. It allow to init, update and sign hash. Hash algorithm
- * depends on SignatureAlgorithm.
- *
- * select (SignatureAlgorithm)
- * { case anonymous: struct { };
- * case rsa:
- * digitally-signed struct {
- * opaque md5_hash[16];
- * opaque sha_hash[20];
- * };
- * case dsa:
- * digitally-signed struct {
- * opaque sha_hash[20];
- * };
- * } Signature;
- *
- * Digital signing description see in TLS spec., 4.7.
- * (http://www.ietf.org/rfc/rfc2246.txt)
- *
- */
-public class DigitalSignature {
-
- private final MessageDigest md5;
- private final MessageDigest sha;
- private final Signature signature;
- private final Cipher cipher;
-
- private byte[] md5_hash;
- private byte[] sha_hash;
-
- /**
- * Create Signature type
- * @param keyExchange
- */
- public DigitalSignature(int keyExchange) {
- try {
- sha = MessageDigest.getInstance("SHA-1");
-
- if (keyExchange == CipherSuite.KeyExchange_RSA_EXPORT ||
- keyExchange == CipherSuite.KeyExchange_RSA ||
- keyExchange == CipherSuite.KeyExchange_DHE_RSA ||
- keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT) {
- // SignatureAlgorithm is rsa
- md5 = MessageDigest.getInstance("MD5");
- cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
- signature = null;
- } else if (keyExchange == CipherSuite.KeyExchange_DHE_DSS ||
- keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT ) {
- // SignatureAlgorithm is dsa
- signature = Signature.getInstance("NONEwithDSA");
- cipher = null;
- md5 = null;
- } else {
- cipher = null;
- signature = null;
- md5 = null;
- }
- } catch (NoSuchAlgorithmException e) {
- // this should never happen
- throw new AssertionError(e);
- } catch (NoSuchPaddingException e) {
- // this should never happen
- throw new AssertionError(e);
- }
- }
-
- /**
- * Initiate Signature type by private key
- * @param key
- */
- public void init(PrivateKey key) {
- try {
- if (signature != null) {
- signature.initSign(key);
- } else if (cipher != null) {
- cipher.init(Cipher.ENCRYPT_MODE, key);
- }
- } catch (InvalidKeyException e){
- throw new AlertException(AlertProtocol.BAD_CERTIFICATE,
- new SSLException("init - invalid private key", e));
- }
- }
-
- /**
- * Initiate Signature type by certificate
- * @param cert
- */
- public void init(Certificate cert) {
- try {
- if (signature != null) {
- signature.initVerify(cert);
- } else if (cipher != null) {
- cipher.init(Cipher.DECRYPT_MODE, cert);
- }
- } catch (InvalidKeyException e){
- throw new AlertException(AlertProtocol.BAD_CERTIFICATE,
- new SSLException("init - invalid certificate", e));
- }
- }
-
- /**
- * Update Signature hash
- * @param data
- */
- public void update(byte[] data) {
- if (sha != null) {
- sha.update(data);
- }
- if (md5 != null) {
- md5.update(data);
- }
- }
-
- /**
- * Sets MD5 hash
- * @param data
- */
- public void setMD5(byte[] data) {
- md5_hash = data;
- }
-
- /**
- * Sets SHA hash
- * @param data
- */
- public void setSHA(byte[] data) {
- sha_hash = data;
- }
-
- /**
- * Sign hash
- * @return Signature bytes
- */
- public byte[] sign() {
- try {
- if (md5 != null && md5_hash == null) {
- md5_hash = new byte[16];
- md5.digest(md5_hash, 0, md5_hash.length);
- }
- if (md5_hash != null) {
- if (signature != null) {
- signature.update(md5_hash);
- } else if (cipher != null) {
- cipher.update(md5_hash);
- }
- }
- if (sha != null && sha_hash == null) {
- sha_hash = new byte[20];
- sha.digest(sha_hash, 0, sha_hash.length);
- }
- if (sha_hash != null) {
- if (signature != null) {
- signature.update(sha_hash);
- } else if (cipher != null) {
- cipher.update(sha_hash);
- }
- }
- if (signature != null) {
- return signature.sign();
- } else if (cipher != null) {
- return cipher.doFinal();
- }
- return new byte[0];
- } catch (DigestException e){
- return new byte[0];
- } catch (SignatureException e){
- return new byte[0];
- } catch (BadPaddingException e){
- return new byte[0];
- } catch (IllegalBlockSizeException e){
- return new byte[0];
- }
- }
-
- /**
- * Verifies the signature data.
- * @param data - the signature bytes
- * @return true if verified
- */
- public boolean verifySignature(byte[] data) {
- if (signature != null) {
- try {
- return signature.verify(data);
- } catch (SignatureException e) {
- return false;
- }
- }
-
- if (cipher != null) {
- final byte[] decrypt;
- try {
- decrypt = cipher.doFinal(data);
- } catch (IllegalBlockSizeException e) {
- return false;
- } catch (BadPaddingException e) {
- return false;
- }
-
- final byte[] md5_sha;
- if (md5_hash != null && sha_hash != null) {
- md5_sha = new byte[md5_hash.length + sha_hash.length];
- System.arraycopy(md5_hash, 0, md5_sha, 0, md5_hash.length);
- System.arraycopy(sha_hash, 0, md5_sha, md5_hash.length, sha_hash.length);
- } else if (md5_hash != null) {
- md5_sha = md5_hash;
- } else {
- md5_sha = sha_hash;
- }
-
- return Arrays.equals(decrypt, md5_sha);
- } else if (data == null || data.length == 0) {
- return true;
- } else {
- return false;
- }
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfBufferException.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfBufferException.java
deleted file mode 100644
index 1dcdd20..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfBufferException.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-
-/**
- * This exception indicates that data could not be read from the stream because the underlying input
- * stream reached its end.
- */
-public class EndOfBufferException extends IOException {
-
- private static final long serialVersionUID = 1838636631255369519L;
-
- public EndOfBufferException() {
- super();
- }
-
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfSourceException.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfSourceException.java
deleted file mode 100644
index 631679a..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/EndOfSourceException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-
-/**
- * This exception indicates that data could not be read from the buffered stream because underlying
- * data buffer was exhausted.
- */
-public class EndOfSourceException extends IOException {
-
- private static final long serialVersionUID = -4673611435974054413L;
-
- public EndOfSourceException() {
- super();
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
deleted file mode 100644
index d438779..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/FileClientSessionCache.java
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLSession;
-import java.util.Map;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.Iterator;
-import java.util.Arrays;
-import java.util.logging.Level;
-import java.io.DataInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-/**
- * File-based cache implementation. Only one process should access the
- * underlying directory at a time.
- */
-public class FileClientSessionCache {
-
- static final int MAX_SIZE = 12; // ~72k
-
- static final java.util.logging.Logger logger
- = java.util.logging.Logger.getLogger(
- FileClientSessionCache.class.getName());
-
- private FileClientSessionCache() {}
-
- /**
- * This cache creates one file per SSL session using "host.port" for
- * the file name. Files are created or replaced when session data is put
- * in the cache (see {@link #putSessionData}). Files are read on
- * cache hits, but not on cache misses.
- *
- * <p>When the number of session files exceeds MAX_SIZE, we delete the
- * least-recently-used file. We don't current persist the last access time,
- * so the ordering actually ends up being least-recently-modified in some
- * cases and even just "not accessed in this process" if the filesystem
- * doesn't track last modified times.
- */
- static class Impl implements SSLClientSessionCache {
-
- /** Directory to store session files in. */
- final File directory;
-
- /**
- * Map of name -> File. Keeps track of the order files were accessed in.
- */
- Map<String, File> accessOrder = newAccessOrder();
-
- /** The number of files on disk. */
- int size;
-
- /**
- * The initial set of files. We use this to defer adding information
- * about all files to accessOrder until necessary.
- */
- String[] initialFiles;
-
- /**
- * Constructs a new cache backed by the given directory.
- */
- Impl(File directory) throws IOException {
- boolean exists = directory.exists();
- if (exists && !directory.isDirectory()) {
- throw new IOException(directory
- + " exists but is not a directory.");
- }
-
- if (exists) {
- // Read and sort initial list of files. We defer adding
- // information about these files to accessOrder until necessary
- // (see indexFiles()). Sorting the list enables us to detect
- // cache misses in getSessionData().
- // Note: Sorting an array here was faster than creating a
- // HashSet on Dalvik.
- initialFiles = directory.list();
- Arrays.sort(initialFiles);
- size = initialFiles.length;
- } else {
- // Create directory.
- if (!directory.mkdirs()) {
- throw new IOException("Creation of " + directory
- + " directory failed.");
- }
- size = 0;
- }
-
- this.directory = directory;
- }
-
- /**
- * Creates a new access-ordered linked hash map.
- */
- private static Map<String, File> newAccessOrder() {
- return new LinkedHashMap<String, File>(
- MAX_SIZE, 0.75f, true /* access order */);
- }
-
- /**
- * Gets the file name for the given host and port.
- */
- private static String fileName(String host, int port) {
- if (host == null) {
- throw new NullPointerException("host");
- }
- return host + "." + port;
- }
-
- public synchronized byte[] getSessionData(String host, int port) {
- /*
- * Note: This method is only called when the in-memory cache
- * in SSLSessionContext misses, so it would be unnecesarily
- * rendundant for this cache to store data in memory.
- */
-
- String name = fileName(host, port);
- File file = accessOrder.get(name);
-
- if (file == null) {
- // File wasn't in access order. Check initialFiles...
- if (initialFiles == null) {
- // All files are in accessOrder, so it doesn't exist.
- return null;
- }
-
- // Look in initialFiles.
- if (Arrays.binarySearch(initialFiles, name) < 0) {
- // Not found.
- return null;
- }
-
- // The file is on disk but not in accessOrder yet.
- file = new File(directory, name);
- accessOrder.put(name, file);
- }
-
- FileInputStream in;
- try {
- in = new FileInputStream(file);
- } catch (FileNotFoundException e) {
- logReadError(host, e);
- return null;
- }
- try {
- int size = (int) file.length();
- byte[] data = new byte[size];
- new DataInputStream(in).readFully(data);
- logger.log(Level.FINE, "Read session for " + host + ".");
- return data;
- } catch (IOException e) {
- logReadError(host, e);
- return null;
- } finally {
- try {
- in.close();
- } catch (IOException e) { /* ignore */ }
- }
- }
-
- static void logReadError(String host, Throwable t) {
- logger.log(Level.INFO, "Error reading session data for " + host
- + ".", t);
- }
-
- public synchronized void putSessionData(SSLSession session,
- byte[] sessionData) {
- String host = session.getPeerHost();
- if (sessionData == null) {
- throw new NullPointerException("sessionData");
- }
-
- String name = fileName(host, session.getPeerPort());
- File file = new File(directory, name);
-
- // Used to keep track of whether or not we're expanding the cache.
- boolean existedBefore = file.exists();
-
- FileOutputStream out;
- try {
- out = new FileOutputStream(file);
- } catch (FileNotFoundException e) {
- // We can't write to the file.
- logWriteError(host, e);
- return;
- }
-
- // If we expanded the cache (by creating a new file)...
- if (!existedBefore) {
- size++;
-
- // Delete an old file if necessary.
- makeRoom();
- }
-
- boolean writeSuccessful = false;
- try {
- out.write(sessionData);
- writeSuccessful = true;
- } catch (IOException e) {
- logWriteError(host, e);
- } finally {
- boolean closeSuccessful = false;
- try {
- out.close();
- closeSuccessful = true;
- } catch (IOException e) {
- logWriteError(host, e);
- } finally {
- if (!writeSuccessful || !closeSuccessful) {
- // Storage failed. Clean up.
- delete(file);
- } else {
- // Success!
- accessOrder.put(name, file);
- logger.log(Level.FINE, "Stored session for " + host
- + ".");
- }
- }
- }
- }
-
- /**
- * Deletes old files if necessary.
- */
- private void makeRoom() {
- if (size <= MAX_SIZE) {
- return;
- }
-
- indexFiles();
-
- // Delete LRUed files.
- int removals = size - MAX_SIZE;
- Iterator<File> i = accessOrder.values().iterator();
- do {
- delete(i.next());
- i.remove();
- } while (--removals > 0);
- }
-
- /**
- * Lazily updates accessOrder to know about all files as opposed to
- * just the files accessed since this process started.
- */
- private void indexFiles() {
- String[] initialFiles = this.initialFiles;
- if (initialFiles != null) {
- this.initialFiles = null;
-
- // Files on disk only, sorted by last modified time.
- // TODO: Use last access time.
- Set<CacheFile> diskOnly = new TreeSet<CacheFile>();
- for (String name : initialFiles) {
- // If the file hasn't been accessed in this process...
- if (!accessOrder.containsKey(name)) {
- diskOnly.add(new CacheFile(directory, name));
- }
- }
-
- if (!diskOnly.isEmpty()) {
- // Add files not accessed in this process to the beginning
- // of accessOrder.
- Map<String, File> newOrder = newAccessOrder();
- for (CacheFile cacheFile : diskOnly) {
- newOrder.put(cacheFile.name, cacheFile);
- }
- newOrder.putAll(accessOrder);
-
- this.accessOrder = newOrder;
- }
- }
- }
-
- @SuppressWarnings("ThrowableInstanceNeverThrown")
- private void delete(File file) {
- if (!file.delete()) {
- logger.log(Level.INFO, "Failed to delete " + file + ".",
- new IOException());
- }
- size--;
- }
-
- static void logWriteError(String host, Throwable t) {
- logger.log(Level.INFO, "Error writing session data for "
- + host + ".", t);
- }
- }
-
- /**
- * Maps directories to the cache instances that are backed by those
- * directories. We synchronize access using the cache instance, so it's
- * important that everyone shares the same instance.
- */
- static final Map<File, FileClientSessionCache.Impl> caches
- = new HashMap<File, FileClientSessionCache.Impl>();
-
- /**
- * Returns a cache backed by the given directory. Creates the directory
- * (including parent directories) if necessary. This cache should have
- * exclusive access to the given directory.
- *
- * @param directory to store files in
- * @return a cache backed by the given directory
- * @throws IOException if the file exists and is not a directory or if
- * creating the directories fails
- */
- public static synchronized SSLClientSessionCache usingDirectory(
- File directory) throws IOException {
- FileClientSessionCache.Impl cache = caches.get(directory);
- if (cache == null) {
- cache = new FileClientSessionCache.Impl(directory);
- caches.put(directory, cache);
- }
- return cache;
- }
-
- /** For testing. */
- static synchronized void reset() {
- caches.clear();
- }
-
- /** A file containing a piece of cached data. */
- static class CacheFile extends File {
-
- final String name;
-
- CacheFile(File dir, String name) {
- super(dir, name);
- this.name = name;
- }
-
- long lastModified = -1;
-
- @Override
- public long lastModified() {
- long lastModified = this.lastModified;
- if (lastModified == -1) {
- lastModified = this.lastModified = super.lastModified();
- }
- return lastModified;
- }
-
- @Override
- public int compareTo(File another) {
- // Sort by last modified time.
- long result = lastModified() - another.lastModified();
- if (result == 0) {
- return super.compareTo(another);
- }
- return result < 0 ? -1 : 1;
- }
- }
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java
deleted file mode 100644
index 6b555c6..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Finished.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-
-import java.io.IOException;
-
-/**
- *
- * Represents Finished message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.9.
- * Finished</a>
- *
- */
-public class Finished extends Message {
-
- // verify data
- private byte[] data;
-
- /**
- * Creates outbound message
- * @param bytes
- */
- public Finished(byte[] bytes) {
- data = bytes;
- length = data.length;
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public Finished(HandshakeIODataStream in, int length)
- throws IOException {
- if (length == 12 || length == 36) {
- data = in.read(length);
- length = data.length;
- } else {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect Finished");
- }
- }
-
- @Override
- public void send(HandshakeIODataStream out) {
- out.write(data);
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.FINISHED;
- }
-
- /**
- * Returns verify data
- * @return
- */
- public byte[] getData() {
- return data;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Handshake.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Handshake.java
deleted file mode 100644
index 64e73dd..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Handshake.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- *
- * This class incapsulates the constants determining the types of handshake
- * messages as defined in TLS 1.0 spec., 7.4. Handshake protocol.
- * (http://www.ietf.org/rfc/rfc2246.txt)
- *
- */
-public class Handshake {
-
- /**
- *
- * hello_request handshake type
- */
- public static final byte HELLO_REQUEST = 0;
-
- /**
- *
- * client_hello handshake type
- */
- public static final byte CLIENT_HELLO = 1;
-
- /**
- *
- * server_hello handshake type
- */
- public static final byte SERVER_HELLO = 2;
-
- /**
- *
- * certificate handshake type
- */
- public static final byte CERTIFICATE = 11;
-
- /**
- *
- * server_key_exchange handshake type
- */
- public static final byte SERVER_KEY_EXCHANGE = 12;
-
- /**
- *
- * certificate_request handshake type
- */
- public static final byte CERTIFICATE_REQUEST = 13;
-
- /**
- *
- * server_hello_done handshake type
- */
- public static final byte SERVER_HELLO_DONE = 14;
-
- /**
- *
- * certificate_verify handshake type
- */
- public static final byte CERTIFICATE_VERIFY = 15;
-
- /**
- *
- * client_key_exchange handshake type
- */
- public static final byte CLIENT_KEY_EXCHANGE = 16;
-
- /**
- *
- * finished handshake type
- */
- public static final byte FINISHED = 20;
-
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java
deleted file mode 100644
index 74cc27d..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeIODataStream.java
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.SSLInputStream;
-
-import java.io.IOException;
-import java.io.PrintStream;
-import java.security.MessageDigest;
-import java.util.Arrays;
-import javax.net.ssl.SSLHandshakeException;
-
-/**
- * This class provides Input/Output data functionality
- * for handshake layer. It provides read and write operations
- * and accumulates all sent/received handshake's data.
- * This class can be presented as a combination of 2 data pipes.
- * The first data pipe is a pipe of income data: append method
- * places the data at the beginning of the pipe, and read methods
- * consume the data from the pipe. The second pipe is an outcoming
- * data pipe: write operations plases the data into the pipe,
- * and getData methods consume the data.
- * It is important to note that work with pipe cound not be
- * started if there is unconsumed data in another pipe. It is
- * reasoned by the following: handshake protocol performs read
- * and write operations consecuently. I.e. it first reads all
- * income data and only than produces the responce and places it
- * into the stream.
- * The read operations of the stream presented by the methods
- * of SSLInputStream which in its turn is an extension of InputStream.
- * So this stream can be used as an InputStream parameter for
- * certificate generation.
- * Also input stream functionality supports marks. The marks
- * help to reset the position of the stream in case of incompleate
- * handshake records. Note that in case of exhausting
- * of income data the EndOfBufferException is thown which implies
- * the following:
- * 1. the stream contains scrappy handshake record,
- * 2. the read position should be reseted to marked,
- * 3. and more income data is expected.
- * The throwing of the exception (instead of returning of -1 value
- * or incompleate filling of destination buffer)
- * helps to speed up the process of scrappy data recognition and
- * processing.
- * For more information about TLS handshake process see
- * TLS v 1 specification at http://www.ietf.org/rfc/rfc2246.txt.
- */
-public class HandshakeIODataStream
- extends SSLInputStream implements org.apache.harmony.xnet.provider.jsse.Appendable, DataStream {
-
- // Objects are used to compute digests of data passed
- // during the handshake phase
- private static final MessageDigest md5;
- private static final MessageDigest sha;
-
- static {
- try {
- md5 = MessageDigest.getInstance("MD5");
- sha = MessageDigest.getInstance("SHA-1");
- } catch (Exception e) {
- e.printStackTrace();
- throw new RuntimeException(
- "Could not initialize the Digest Algorithms.");
- }
- }
-
- public HandshakeIODataStream() {}
-
- // buffer is used to keep the handshaking data;
- private int buff_size = 1024;
- private int inc_buff_size = 1024;
- private byte[] buffer = new byte[buff_size];
-
-
- // ---------------- Input related functionality -----------------
-
- // position of the next byte to read
- private int read_pos;
- private int marked_pos;
- // position of the last byte to read + 1
- private int read_pos_end;
-
- @Override
- public int available() {
- return read_pos_end - read_pos;
- }
-
- @Override
- public boolean markSupported() {
- return true;
- }
-
- @Override
- public void mark(int limit) {
- marked_pos = read_pos;
- }
-
- public void mark() {
- marked_pos = read_pos;
- }
-
- @Override
- public void reset() {
- read_pos = marked_pos;
- }
-
- /**
- * Removes the data from the marked position to
- * the current read position. The method is usefull when it is needed
- * to delete one message from the internal buffer.
- */
- protected void removeFromMarkedPosition() {
- System.arraycopy(buffer, read_pos,
- buffer, marked_pos, read_pos_end - read_pos);
- read_pos_end -= (read_pos - marked_pos);
- read_pos = marked_pos;
- }
-
- /**
- * read an opaque value;
- * @param byte: byte
- * @return
- */
- @Override
- public int read() throws IOException {
- if (read_pos == read_pos_end) {
- //return -1;
- throw new EndOfBufferException();
- }
- return buffer[read_pos++] & 0xFF;
- }
-
- /**
- * reads vector of opaque values
- * @param new: long
- * @return
- */
- @Override
- public byte[] read(int length) throws IOException {
- if (length > available()) {
- throw new EndOfBufferException();
- }
- byte[] res = new byte[length];
- System.arraycopy(buffer, read_pos, res, 0, length);
- read_pos = read_pos + length;
- return res;
- }
-
- @Override
- public int read(byte[] dest, int offset, int length) throws IOException {
- if (length > available()) {
- throw new EndOfBufferException();
- }
- System.arraycopy(buffer, read_pos, dest, offset, length);
- read_pos = read_pos + length;
- return length;
- }
-
- // ------------------- Extending of the input data ---------------------
-
- /**
- * Appends the income data to be read by handshake protocol.
- * The attempts to overflow the buffer by means of this methods
- * seem to be futile because of:
- * 1. The SSL protocol specifies the maximum size of the record
- * and record protocol does not pass huge messages.
- * (see TLS v1 specification http://www.ietf.org/rfc/rfc2246.txt ,
- * p 6.2)
- * 2. After each call of this method, handshake protocol should
- * start (and starts) the operations on received data and recognize
- * the fake data if such was provided (to check the size of certificate
- * for example).
- */
- public void append(byte[] src) {
- append(src, 0, src.length);
- }
-
- private void append(byte[] src, int from, int length) {
- if (read_pos == read_pos_end) {
- // start reading state after writing
- if (write_pos_beg != write_pos) {
- // error: outboud handshake data was not sent,
- // but inbound handshake data has been received.
- throw new AlertException(
- AlertProtocol.UNEXPECTED_MESSAGE,
- new SSLHandshakeException(
- "Handshake message has been received before "
- + "the last oubound message had been sent."));
- }
- if (read_pos < write_pos) {
- read_pos = write_pos;
- read_pos_end = read_pos;
- }
- }
- if (read_pos_end + length > buff_size) {
- enlargeBuffer(read_pos_end+length-buff_size);
- }
- System.arraycopy(src, from, buffer, read_pos_end, length);
- read_pos_end += length;
- }
-
- private void enlargeBuffer(int size) {
- buff_size = (size < inc_buff_size)
- ? buff_size + inc_buff_size
- : buff_size + size;
- byte[] new_buff = new byte[buff_size];
- System.arraycopy(buffer, 0, new_buff, 0, buffer.length);
- buffer = new_buff;
- }
-
- protected void clearBuffer() {
- read_pos = 0;
- marked_pos = 0;
- read_pos_end = 0;
- write_pos = 0;
- write_pos_beg = 0;
- Arrays.fill(buffer, (byte) 0);
- }
-
- // ------------------- Output related functionality --------------------
-
- // position in the buffer available for write
- private int write_pos;
- // position in the buffer where the last write session has begun
- private int write_pos_beg;
-
- // checks if the data can be written in the buffer
- private void check(int length) {
- // (write_pos == write_pos_beg) iff:
- // 1. there were not write operations yet
- // 2. all written data was demanded by getData methods
- if (write_pos == write_pos_beg) {
- // just started to write after the reading
- if (read_pos != read_pos_end) {
- // error: attempt to write outbound data into the stream before
- // all the inbound handshake data had been read
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLHandshakeException("Data was not fully read: "
- + read_pos + " " + read_pos_end));
- }
- // set up the write positions
- if (write_pos_beg < read_pos_end) {
- write_pos_beg = read_pos_end;
- write_pos = write_pos_beg;
- }
- }
- // if there is not enought free space in the buffer - enlarge it:
- if (write_pos + length >= buff_size) {
- enlargeBuffer(length);
- }
- }
-
- /**
- * Writes an opaque value
- * @param byte: byte
- */
- public void write(byte b) {
- check(1);
- buffer[write_pos++] = b;
- }
-
- /**
- * Writes Uint8 value
- * @param long: the value to be written (last byte)
- */
- public void writeUint8(long n) {
- check(1);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * Writes Uint16 value
- * @param long: the value to be written (last 2 bytes)
- */
- public void writeUint16(long n) {
- check(2);
- buffer[write_pos++] = (byte) ((n & 0x00ff00) >> 8);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * Writes Uint24 value
- * @param long: the value to be written (last 3 bytes)
- */
- public void writeUint24(long n) {
- check(3);
- buffer[write_pos++] = (byte) ((n & 0x00ff0000) >> 16);
- buffer[write_pos++] = (byte) ((n & 0x00ff00) >> 8);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * Writes Uint32 value
- * @param long: the value to be written (last 4 bytes)
- */
- public void writeUint32(long n) {
- check(4);
- buffer[write_pos++] = (byte) ((n & 0x00ff000000) >> 24);
- buffer[write_pos++] = (byte) ((n & 0x00ff0000) >> 16);
- buffer[write_pos++] = (byte) ((n & 0x00ff00) >> 8);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * Writes Uint64 value
- * @param long: the value to be written
- */
- public void writeUint64(long n) {
- check(8);
- buffer[write_pos++] = (byte) ((n & 0x00ff00000000000000L) >> 56);
- buffer[write_pos++] = (byte) ((n & 0x00ff000000000000L) >> 48);
- buffer[write_pos++] = (byte) ((n & 0x00ff0000000000L) >> 40);
- buffer[write_pos++] = (byte) ((n & 0x00ff00000000L) >> 32);
- buffer[write_pos++] = (byte) ((n & 0x00ff000000) >> 24);
- buffer[write_pos++] = (byte) ((n & 0x00ff0000) >> 16);
- buffer[write_pos++] = (byte) ((n & 0x00ff00) >> 8);
- buffer[write_pos++] = (byte) (n & 0x00ff);
- }
-
- /**
- * writes vector of opaque values
- * @param vector the vector to be written
- */
- public void write(byte[] vector) {
- check(vector.length);
- System.arraycopy(vector, 0, buffer, write_pos, vector.length);
- write_pos += vector.length;
- }
-
- // ------------------- Retrieve the written bytes ----------------------
-
- public boolean hasData() {
- return (write_pos > write_pos_beg);
- }
-
- /**
- * returns the chunk of stored data with the length no more than specified.
- * @param length: int
- * @return
- */
- public byte[] getData(int length) {
- byte[] res;
- if (write_pos - write_pos_beg < length) {
- res = new byte[write_pos - write_pos_beg];
- System.arraycopy(buffer, write_pos_beg,
- res, 0, write_pos-write_pos_beg);
- write_pos_beg = write_pos;
- } else {
- res = new byte[length];
- System.arraycopy(buffer, write_pos_beg, res, 0, length);
- write_pos_beg += length;
- }
- return res;
- }
-
- // ---------------------- Debud functionality -------------------------
-
- protected void printContent(PrintStream outstream) {
- int perLine = 20;
- String prefix = " ";
- String delimiter = "";
-
- for (int i=write_pos_beg; i<write_pos; i++) {
- String tail = Integer.toHexString(
- 0x00ff & buffer[i]).toUpperCase();
- if (tail.length() == 1) {
- tail = "0" + tail;
- }
- outstream.print(prefix + tail + delimiter);
-
- if (((i-write_pos_beg+1)%10) == 0) {
- outstream.print(" ");
- }
-
- if (((i-write_pos_beg+1)%perLine) == 0) {
- outstream.println();
- }
- }
- outstream.println();
- }
-
- // ---------------------- Message Digest Functionality ----------------
-
- /**
- * Returns the MD5 digest of the data passed throught the stream
- * @return MD5 digest
- */
- protected byte[] getDigestMD5() {
- synchronized (md5) {
- int len = (read_pos_end > write_pos)
- ? read_pos_end
- : write_pos;
- md5.update(buffer, 0, len);
- return md5.digest();
- }
- }
-
- /**
- * Returns the SHA-1 digest of the data passed throught the stream
- * @return SHA-1 digest
- */
- protected byte[] getDigestSHA() {
- synchronized (sha) {
- int len = (read_pos_end > write_pos)
- ? read_pos_end
- : write_pos;
- sha.update(buffer, 0, len);
- return sha.digest();
- }
- }
-
- /**
- * Returns the MD5 digest of the data passed throught the stream
- * except last message
- * @return MD5 digest
- */
- protected byte[] getDigestMD5withoutLast() {
- synchronized (md5) {
- md5.update(buffer, 0, marked_pos);
- return md5.digest();
- }
- }
-
- /**
- * Returns the SHA-1 digest of the data passed throught the stream
- * except last message
- * @return SHA-1 digest
- */
- protected byte[] getDigestSHAwithoutLast() {
- synchronized (sha) {
- sha.update(buffer, 0, marked_pos);
- return sha.digest();
- }
- }
-
- /**
- * Returns all the data passed throught the stream
- * @return all the data passed throught the stream at the moment
- */
- protected byte[] getMessages() {
- int len = (read_pos_end > write_pos) ? read_pos_end : write_pos;
- byte[] res = new byte[len];
- System.arraycopy(buffer, 0, res, 0, len);
- return res;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java
deleted file mode 100644
index 6579398..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HandshakeProtocol.java
+++ /dev/null
@@ -1,534 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.math.BigInteger;
-import java.security.GeneralSecurityException;
-import java.security.KeyFactory;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.PublicKey;
-import java.security.interfaces.RSAKey;
-import java.security.spec.InvalidKeySpecException;
-import java.security.spec.RSAPublicKeySpec;
-import java.util.Arrays;
-import java.util.Vector;
-
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-
-/**
- * Base class for ClientHandshakeImpl and ServerHandshakeImpl classes.
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.
- * Handshake protocol</a>
- *
- */
-public abstract class HandshakeProtocol {
-
- /**
- * Handshake status NEED_UNWRAP - HandshakeProtocol needs to receive data
- */
- public final static int NEED_UNWRAP = 1;
-
- /**
- * Handshake status NOT_HANDSHAKING - is not currently handshaking
- */
- public final static int NOT_HANDSHAKING = 2;
-
- /**
- * Handshake status FINISHED - HandshakeProtocol has just finished
- */
- public final static int FINISHED = 3;
-
- /**
- * Handshake status NEED_TASK - HandshakeProtocol needs the results of delegated task
- */
- public final static int NEED_TASK = 4;
-
- /**
- * Current handshake status
- */
- protected int status = NOT_HANDSHAKING;
-
- /**
- * IO stream for income/outcome handshake data
- */
- protected HandshakeIODataStream io_stream = new HandshakeIODataStream();
-
- /**
- * SSL Record Protocol implementation.
- */
- protected SSLRecordProtocol recordProtocol;
-
- /**
- * SSLParameters suplied by SSLSocket or SSLEngine
- */
- protected SSLParameters parameters;
-
- /**
- * Delegated tasks for this handshake implementation
- */
- protected Vector<DelegatedTask> delegatedTasks = new Vector<DelegatedTask>();
-
- /**
- * Indicates non-blocking handshake
- */
- protected boolean nonBlocking;
-
- /**
- * Pending session
- */
- protected SSLSessionImpl session;
-
- /**
- * Sended and received handshake messages
- */
- protected ClientHello clientHello;
- protected ServerHello serverHello;
- protected CertificateMessage serverCert;
- protected ServerKeyExchange serverKeyExchange;
- protected CertificateRequest certificateRequest;
- protected ServerHelloDone serverHelloDone;
- protected CertificateMessage clientCert;
- protected ClientKeyExchange clientKeyExchange;
- protected CertificateVerify certificateVerify;
- protected Finished clientFinished;
- protected Finished serverFinished;
-
- /**
- * Indicates that change cipher spec message has been received
- */
- protected boolean changeCipherSpecReceived = false;
-
- /**
- * Indicates previous session resuming
- */
- protected boolean isResuming = false;
-
- /**
- * Premaster secret
- */
- protected byte[] preMasterSecret;
-
- /**
- * Exception occured in delegated task
- */
- protected Exception delegatedTaskErr;
-
- // reference verify_data used to verify finished message
- private byte[] verify_data = new byte[12];
-
- // Encoding of "master secret" string: "master secret".getBytes()
- private byte[] master_secret_bytes =
- {109, 97, 115, 116, 101, 114, 32, 115, 101, 99, 114, 101, 116 };
-
- // indicates whether protocol needs to send change cipher spec message
- private boolean needSendCCSpec = false;
-
- // indicates whether protocol needs to send change cipher spec message
- protected boolean needSendHelloRequest = false;
-
- /**
- * SSLEngine owning this HandshakeProtocol
- */
- public SSLEngineImpl engineOwner;
-
- /**
- * SSLSocket owning this HandshakeProtocol
- */
- // BEGIN android-removed
- // public SSLSocketImpl socketOwner;
- // END android-removed
-
- /**
- * Creates HandshakeProtocol instance
- * @param owner
- */
- protected HandshakeProtocol(Object owner) {
- if (owner instanceof SSLEngineImpl) {
- engineOwner = (SSLEngineImpl) owner;
- nonBlocking = true;
- this.parameters = engineOwner.sslParameters;
- }
- // BEGIN android-removed
- // else if (owner instanceof SSLSocketImpl) {
- // socketOwner = (SSLSocketImpl) owner;
- // nonBlocking = false;
- // this.parameters = socketOwner.sslParameters;
- // }
- // END android-removed
- }
-
- /**
- * Sets SSL Record Protocol
- * @param recordProtocol
- */
- public void setRecordProtocol(SSLRecordProtocol recordProtocol) {
- this.recordProtocol = recordProtocol;
- }
-
- /**
- * Start session negotiation
- * @param session
- */
- public abstract void start();
-
- /**
- * Stops the current session renegotiation process.
- * Such functionality is needed when it is session renegotiation
- * process and no_renegotiation alert message is received
- * from another peer.
- * @param session
- */
- protected void stop() {
- clearMessages();
- status = NOT_HANDSHAKING;
- }
-
- /**
- * Returns handshake status
- * @return
- */
- public SSLEngineResult.HandshakeStatus getStatus() {
- if (io_stream.hasData() || needSendCCSpec ||
- needSendHelloRequest || delegatedTaskErr != null) {
- return SSLEngineResult.HandshakeStatus.NEED_WRAP;
- }
- if (!delegatedTasks.isEmpty()) {
- return SSLEngineResult.HandshakeStatus.NEED_TASK;
- }
-
- switch (status) {
- case HandshakeProtocol.NEED_UNWRAP:
- return SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
- case HandshakeProtocol.FINISHED:
- status = NOT_HANDSHAKING;
- clearMessages();
- return SSLEngineResult.HandshakeStatus.FINISHED;
- default: // HandshakeProtocol.NOT_HANDSHAKING:
- return SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
- }
- }
-
- /**
- * Returns pending session
- * @return session
- */
- public SSLSessionImpl getSession() {
- return session;
- }
-
- protected void sendChangeCipherSpec() {
- needSendCCSpec = true;
- }
-
- protected void sendHelloRequest() {
- needSendHelloRequest = true;
- }
-
- /**
- * Proceses inbound ChangeCipherSpec message
- */
- abstract void receiveChangeCipherSpec();
-
- /**
- * Creates and sends finished message
- */
- abstract void makeFinished();
-
- /**
- * Proceses inbound handshake messages
- * @param bytes
- */
- public abstract void unwrap(byte[] bytes);
-
- /**
- * Processes SSLv2 Hello message
- * @param bytes
- */
- public abstract void unwrapSSLv2(byte[] bytes);
-
- /**
- * Proceses outbound handshake messages
- * @return
- */
- public byte[] wrap() {
- if (delegatedTaskErr != null) {
- // process error occured in delegated task
- Exception e = delegatedTaskErr;
- delegatedTaskErr = null;
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "Error occured in delegated task:" + e.getMessage(), e);
- }
- if (io_stream.hasData()) {
- return recordProtocol.wrap(ContentType.HANDSHAKE, io_stream);
- } else if (needSendCCSpec) {
- makeFinished();
- needSendCCSpec = false;
- return recordProtocol.getChangeCipherSpecMesage(getSession());
- } else if (needSendHelloRequest) {
- needSendHelloRequest = false;
- return recordProtocol.wrap(ContentType.HANDSHAKE,
- // hello request message
- // (see TLS v 1 specification:
- // http://www.ietf.org/rfc/rfc2246.txt)
- new byte[] {0, 0, 0, 0}, 0, 4);
- } else {
- return null; // nothing to send;
- }
- }
-
- /**
- * Sends fatal alert, breaks execution
- *
- * @param description
- */
- protected void sendWarningAlert(byte description) {
- recordProtocol.alert(AlertProtocol.WARNING, description);
- }
-
- /**
- * Sends fatal alert, breaks execution
- *
- * @param description
- * @param reason
- */
- protected void fatalAlert(byte description, String reason) {
- throw new AlertException(description, new SSLHandshakeException(reason));
- }
-
- /**
- * Sends fatal alert, breaks execution
- *
- * @param description
- * @param reason
- * @param cause
- */
- protected void fatalAlert(byte description, String reason, Exception cause) {
- throw new AlertException(description, new SSLException(reason, cause));
- }
-
- /**
- * Sends fatal alert, breaks execution
- *
- * @param description
- * @param cause
- */
- protected void fatalAlert(byte description, SSLException cause) {
- throw new AlertException(description, cause);
- }
-
- /**
- * Computers reference TLS verify_data that is used to verify finished message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS spec. 7.4.9. Finished</a>
- * @param label
- */
- protected void computerReferenceVerifyDataTLS(String label) {
- computerVerifyDataTLS(label, verify_data);
- }
-
- /**
- * Computer TLS verify_data
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS spec. 7.4.9. Finished</a>
- * @param label
- * @param buf
- */
- protected void computerVerifyDataTLS(String label, byte[] buf) {
- byte[] md5_digest = io_stream.getDigestMD5();
- byte[] sha_digest = io_stream.getDigestSHA();
-
- byte[] digest = new byte[md5_digest.length + sha_digest.length];
- System.arraycopy(md5_digest, 0, digest, 0, md5_digest.length);
- System.arraycopy(sha_digest, 0, digest, md5_digest.length,
- sha_digest.length);
- try {
- PRF.computePRF(buf, session.master_secret,
- label.getBytes(), digest);
- } catch (GeneralSecurityException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "PRF error", e);
- }
- }
-
- /**
- * Computer reference SSLv3 verify_data that is used to verify finished message
- * @see "SSLv3 spec. 7.6.9. Finished"
- * @param label
- */
- protected void computerReferenceVerifyDataSSLv3(byte[] sender) {
- verify_data = new byte[36];
- computerVerifyDataSSLv3(sender, verify_data);
- }
-
- /**
- * Computer SSLv3 verify_data
- * @see "SSLv3 spec. 7.6.9. Finished"
- * @param label
- * @param buf
- */
- protected void computerVerifyDataSSLv3(byte[] sender, byte[] buf) {
- MessageDigest md5;
- MessageDigest sha;
- try {
- md5 = MessageDigest.getInstance("MD5");
- sha = MessageDigest.getInstance("SHA-1");
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "Could not initialize the Digest Algorithms.", e);
- return;
- }
- try {
- byte[] hanshake_messages = io_stream.getMessages();
- md5.update(hanshake_messages);
- md5.update(sender);
- md5.update(session.master_secret);
- byte[] b = md5.digest(SSLv3Constants.MD5pad1);
- md5.update(session.master_secret);
- md5.update(SSLv3Constants.MD5pad2);
- System.arraycopy(md5.digest(b), 0, buf, 0, 16);
-
- sha.update(hanshake_messages);
- sha.update(sender);
- sha.update(session.master_secret);
- b = sha.digest(SSLv3Constants.SHApad1);
- sha.update(session.master_secret);
- sha.update(SSLv3Constants.SHApad2);
- System.arraycopy(sha.digest(b), 0, buf, 16, 20);
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
-
- }
- }
-
- /**
- * Verifies finished data
- *
- * @param data
- * @param isServer
- */
- protected void verifyFinished(byte[] data) {
- if (!Arrays.equals(verify_data, data)) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "Incorrect FINISED");
- }
- }
-
- /**
- * Sends fatal alert "UNEXPECTED MESSAGE"
- *
- */
- protected void unexpectedMessage() {
- fatalAlert(AlertProtocol.UNEXPECTED_MESSAGE, "UNEXPECTED MESSAGE");
- }
-
- /**
- * Writes message to HandshakeIODataStream
- *
- * @param message
- */
- public void send(Message message) {
- io_stream.writeUint8(message.getType());
- io_stream.writeUint24(message.length());
- message.send(io_stream);
- }
-
- /**
- * Computers master secret
- *
- */
- public void computerMasterSecret() {
- byte[] seed = new byte[64];
- System.arraycopy(clientHello.getRandom(), 0, seed, 0, 32);
- System.arraycopy(serverHello.getRandom(), 0, seed, 32, 32);
- session.master_secret = new byte[48];
- if (serverHello.server_version[1] == 1) { // TLSv1
- try {
- PRF.computePRF(session.master_secret, preMasterSecret,
- master_secret_bytes, seed);
- } catch (GeneralSecurityException e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "PRF error", e);
- }
- } else { // SSL3.0
- PRF.computePRF_SSLv3(session.master_secret, preMasterSecret, seed);
- }
-
- //delete preMasterSecret from memory
- Arrays.fill(preMasterSecret, (byte)0);
- preMasterSecret = null;
- }
-
- /**
- * Returns a delegated task.
- * @return Delegated task or null
- */
- public Runnable getTask() {
- if (delegatedTasks.isEmpty()) {
- return null;
- }
- return delegatedTasks.remove(0);
- }
-
- /**
- *
- * Clears previously sended and received handshake messages
- */
- protected void clearMessages() {
- io_stream.clearBuffer();
- clientHello = null;
- serverHello = null;
- serverCert = null;
- serverKeyExchange = null;
- certificateRequest = null;
- serverHelloDone = null;
- clientCert = null;
- clientKeyExchange = null;
- certificateVerify = null;
- clientFinished = null;
- serverFinished = null;
- }
-
- /**
- * Returns RSA key length
- * @param pk
- * @return
- * @throws NoSuchAlgorithmException
- * @throws InvalidKeySpecException
- */
- protected static int getRSAKeyLength(PublicKey pk)
- throws NoSuchAlgorithmException, InvalidKeySpecException {
-
- BigInteger mod;
- if (pk instanceof RSAKey) {
- mod = ((RSAKey) pk).getModulus();
- } else {
- KeyFactory kf = KeyFactory.getInstance("RSA");
- mod = kf.getKeySpec(pk, RSAPublicKeySpec.class)
- .getModulus();
- }
- return mod.bitLength();
- }
-
- /**
- * Shutdownes the protocol. It will be impossiblke to use the instance
- * after the calling of this method.
- */
- protected void shutdown() {
- clearMessages();
- session = null;
- preMasterSecret = null;
- delegatedTasks.clear();
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HelloRequest.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HelloRequest.java
deleted file mode 100644
index 40d4a71..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/HelloRequest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-import org.apache.harmony.xnet.provider.jsse.Handshake;
-import org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream;
-
-import java.io.IOException;
-
-/**
- *
- * Represents Hello Request message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.1.1.
- * Hello request</a>
- *
- */
-public class HelloRequest extends Message {
-
- /**
- * Creates outbound message
- *
- */
- public HelloRequest() {
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public HelloRequest(HandshakeIODataStream in, int length)
- throws IOException {
- if (length != 0) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect HelloRequest");
- }
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- }
-
- @Override
- public int length() {
- return 0;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.HELLO_REQUEST;
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java
deleted file mode 100644
index 083a342..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/JSSEProvider.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-import java.security.Provider;
-
-/**
- * JSSE Provider implementation.
- *
- * This implementation is based on TLS v 1.0 and SSL v3 protocol specifications.
- *
- * <ul>
- * <li><a href="http://www.ietf.org/rfc/rfc2246.txt">TLS v 1.0 Protocol
- * specification</a></li>
- * <li><a href="http://wp.netscape.com/eng/ssl3">SSL v3 Protocol
- * specification</a></li>
- * </ul>
- *
- * Provider implementation supports the following cipher suites:
- * TLS_NULL_WITH_NULL_NULL
- * TLS_RSA_WITH_NULL_MD5
- * TLS_RSA_WITH_NULL_SHA
- * TLS_RSA_EXPORT_WITH_RC4_40_MD5
- * TLS_RSA_WITH_RC4_128_MD5
- * TLS_RSA_WITH_RC4_128_SHA
- * TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5
- * TLS_RSA_WITH_IDEA_CBC_SHA
- * TLS_RSA_EXPORT_WITH_DES40_CBC_SHA
- * TLS_RSA_WITH_DES_CBC_SHA
- * TLS_RSA_WITH_3DES_EDE_CBC_SHA
- * TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DH_DSS_WITH_DES_CBC_SHA
- * TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA
- * TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DH_RSA_WITH_DES_CBC_SHA
- * TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA
- * TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DHE_DSS_WITH_DES_CBC_SHA
- * TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA
- * TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DHE_RSA_WITH_DES_CBC_SHA
- * TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA
- * TLS_DH_anon_EXPORT_WITH_RC4_40_MD5
- * TLS_DH_anon_WITH_RC4_128_MD5
- * TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA
- * TLS_DH_anon_WITH_DES_CBC_SHA
- * TLS_DH_anon_WITH_3DES_EDE_CBC_SHA
- *
- * The real set of available cipher suites depends on set of available
- * crypto algorithms. These algorithms must be provided by some crypto
- * provider.
- *
- * The following cipher algorithms are used by different cipher suites:
- * IDEA/CBC/NoPadding
- * RC2/CBC/NoPadding
- * RC4
- * DES/CBC/NoPadding
- * DES/CBC/NoPadding
- * DESede/CBC/NoPadding
- *
- * Also the current JSSE provider implementation uses the following
- * crypto algorithms:
- *
- * Algorithms that MUST be provided by crypto provider:
- * Mac HmacMD5
- * Mac HmacSHA1
- * MessageDigest MD5
- * MessageDigest SHA-1
- * CertificateFactory X509
- *
- * The cipher suites with RSA key exchange may also require:
- * Cipher RSA
- * KeyPairGenerator RSA
- * KeyFactory RSA
- *
- * The cipher suites with DH key exchange may also require:
- * Signature NONEwithDSA
- * KeyPairGenerator DiffieHellman or DH
- * KeyFactory DiffieHellman or DH
- * KeyAgreement DiffieHellman or DH
- * KeyPairGenerator DiffieHellman or DH
- *
- * Trust manager implementation requires:
- * CertPathValidator PKIX
- * CertificateFactory X509
- *
- */
-public final class JSSEProvider extends Provider {
-
- private static final long serialVersionUID = 3075686092260669675L;
-
- public JSSEProvider() {
- super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
- AccessController.doPrivileged(new PrivilegedAction<Void>() {
- public Void run() {
- put("SSLContext.TLS", SSLContextImpl.class.getName());
- put("Alg.Alias.SSLContext.TLSv1", "TLS");
- put("KeyManagerFactory.X509", KeyManagerFactoryImpl.class.getName());
- put("TrustManagerFactory.X509", TrustManagerFactoryImpl.class.getName());
- // BEGIN android-added
- put("SSLContext.SSL", SSLContextImpl.class.getName());
- put("Alg.Alias.SSLContext.SSLv3", "SSL");
- put("MessageDigest.SHA-1", "org.apache.harmony.xnet.provider.jsse.OpenSSLMessageDigestJDK$SHA1");
- put("Alg.Alias.MessageDigest.SHA1", "SHA-1");
- put("Alg.Alias.MessageDigest.SHA", "SHA-1");
- put("Alg.Alias.MessageDigest.1.3.14.3.2.26", "SHA-1");
- put("MessageDigest.SHA-224", "org.apache.harmony.xnet.provider.jsse.OpenSSLMessageDigestJDK$SHA224");
- put("Alg.Alias.MessageDigest.SHA224", "SHA-224");
- put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.4", "SHA-224");
- put("MessageDigest.SHA-256", "org.apache.harmony.xnet.provider.jsse.OpenSSLMessageDigestJDK$SHA256");
- put("Alg.Alias.MessageDigest.SHA256", "SHA-256");
- put("Alg.Alias.MessageDigest.2.16.840.1.101.3.4.2.1", "SHA-256");
- put("MessageDigest.MD5", "org.apache.harmony.xnet.provider.jsse.OpenSSLMessageDigestJDK$MD5");
- put("Alg.Alias.MessageDigest.1.2.840.113549.2.5", "MD5");
- // END android-added
- return null;
- }
- });
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java
deleted file mode 100644
index 3b55299..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerFactoryImpl.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactorySpi;
-import javax.net.ssl.ManagerFactoryParameters;
-
-/**
- * KeyManagerFactory implementation.
- * @see javax.net.ssl.KeyManagerFactorySpi
- */
-public class KeyManagerFactoryImpl extends KeyManagerFactorySpi {
-
- // source of key material
- private KeyStore keyStore;
-
- //password
- private char[] pwd;
-
- /**
- * @see javax.net.ssl.KeyManagerFactorySpi#engineInit(KeyStore ks, char[]
- * password)
- */
- @Override
- public void engineInit(KeyStore ks, char[] password)
- throws KeyStoreException, NoSuchAlgorithmException,
- UnrecoverableKeyException {
- if (ks != null) {
- keyStore = ks;
- if (password != null) {
- pwd = password.clone();
- } else {
- pwd = new char[0];
- }
- } else {
- keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- String keyStoreName = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System.getProperty("javax.net.ssl.keyStore");
- }
- });
- String keyStorePwd = null;
- if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE")
- || keyStoreName.length() == 0) {
- try {
- keyStore.load(null, null);
- } catch (IOException e) {
- throw new KeyStoreException(e);
- } catch (CertificateException e) {
- throw new KeyStoreException(e);
- }
- } else {
- keyStorePwd = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.keyStorePassword");
- }
- });
- if (keyStorePwd == null) {
- pwd = new char[0];
- } else {
- pwd = keyStorePwd.toCharArray();
- }
- try {
- keyStore.load(new FileInputStream(new File(keyStoreName)),
- pwd);
-
- } catch (FileNotFoundException e) {
- throw new KeyStoreException(e);
- } catch (IOException e) {
- throw new KeyStoreException(e);
- } catch (CertificateException e) {
- throw new KeyStoreException(e);
- }
- }
-
- }
-
- }
-
- /**
- * @see javax.net.ssl.KeyManagerFactorySpi#engineInit(ManagerFactoryParameters
- * spec)
- */
- @Override
- public void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException {
- throw new InvalidAlgorithmParameterException(
- "ManagerFactoryParameters not supported");
-
- }
-
- /**
- * @see javax.net.ssl.KeyManagerFactorySpi#engineGetKeyManagers()
- */
- @Override
- public KeyManager[] engineGetKeyManagers() {
- if (keyStore == null) {
- throw new IllegalStateException("KeyManagerFactory is not initialized");
- }
- return new KeyManager[] { new KeyManagerImpl(keyStore, pwd) };
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java
deleted file mode 100644
index f63170f..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/KeyManagerImpl.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.net.Socket;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.Principal;
-import java.security.PrivateKey;
-import java.security.UnrecoverableEntryException;
-import java.security.KeyStore.PrivateKeyEntry;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import java.util.Enumeration;
-import java.util.Hashtable;
-import java.util.Vector;
-
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.X509ExtendedKeyManager;
-import javax.security.auth.x500.X500Principal;
-
-/**
- * KeyManager implementation.
- *
- * This implementation uses hashed key store information. It works faster than retrieving all of the
- * data from the key store. Any key store changes, that happen after key manager was created, have
- * no effect. The implementation does not use peer information (host, port) that may be obtained
- * from socket or engine.
- *
- * @see javax.net.ssl.KeyManager
- *
- */
-public class KeyManagerImpl extends X509ExtendedKeyManager {
-
- // hashed key store information
- private final Hashtable<String, PrivateKeyEntry> hash;
-
- /**
- * Creates Key manager
- *
- * @param keyStore
- * @param pwd
- */
- public KeyManagerImpl(KeyStore keyStore, char[] pwd) {
- super();
- this.hash = new Hashtable<String, PrivateKeyEntry>();
- final Enumeration<String> aliases;
- try {
- aliases = keyStore.aliases();
- } catch (KeyStoreException e) {
- return;
- }
- for (; aliases.hasMoreElements();) {
- final String alias = aliases.nextElement();
- try {
- if (keyStore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) {
- final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore
- .getEntry(alias, new KeyStore.PasswordProtection(pwd));
- hash.put(alias, entry);
- }
- } catch (KeyStoreException e) {
- continue;
- } catch (UnrecoverableEntryException e) {
- continue;
- } catch (NoSuchAlgorithmException e) {
- continue;
- }
- }
- }
-
- public String chooseClientAlias(String[] keyType, Principal[] issuers, Socket socket) {
- final String[] al = chooseAlias(keyType, issuers);
- return (al == null ? null : al[0]);
- }
-
- public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
- final String[] al = chooseAlias(new String[] { keyType }, issuers);
- return (al == null ? null : al[0]);
- }
-
- public X509Certificate[] getCertificateChain(String alias) {
- // BEGIN android-changed
- if (alias == null) {
- return null;
- }
- // END android-changed
- if (hash.containsKey(alias)) {
- Certificate[] certs = hash.get(alias).getCertificateChain();
- if (certs[0] instanceof X509Certificate) {
- X509Certificate[] xcerts = new X509Certificate[certs.length];
- for (int i = 0; i < certs.length; i++) {
- xcerts[i] = (X509Certificate) certs[i];
- }
- return xcerts;
- }
- }
- return null;
-
- }
-
- public String[] getClientAliases(String keyType, Principal[] issuers) {
- return chooseAlias(new String[] { keyType }, issuers);
- }
-
- public String[] getServerAliases(String keyType, Principal[] issuers) {
- return chooseAlias(new String[] { keyType }, issuers);
- }
-
- public PrivateKey getPrivateKey(String alias) {
- // BEGIN android-changed
- if (alias == null) {
- return null;
- }
- // END android-changed
- if (hash.containsKey(alias)) {
- return hash.get(alias).getPrivateKey();
- }
- return null;
- }
-
- @Override
- public String chooseEngineClientAlias(String[] keyType, Principal[] issuers, SSLEngine engine) {
- final String[] al = chooseAlias(keyType, issuers);
- return (al == null ? null : al[0]);
- }
-
- @Override
- public String chooseEngineServerAlias(String keyType, Principal[] issuers, SSLEngine engine) {
- final String[] al = chooseAlias(new String[] { keyType }, issuers);
- return (al == null ? null : al[0]);
- }
-
- private String[] chooseAlias(String[] keyType, Principal[] issuers) {
- if (keyType == null || keyType.length == 0) {
- return null;
- }
- Vector<String> found = new Vector<String>();
- for (Enumeration<String> aliases = hash.keys(); aliases.hasMoreElements();) {
- final String alias = aliases.nextElement();
- final KeyStore.PrivateKeyEntry entry = hash.get(alias);
- final Certificate[] certs = entry.getCertificateChain();
- final String alg = certs[0].getPublicKey().getAlgorithm();
- for (int i = 0; i < keyType.length; i++) {
- if (alg.equals(keyType[i])) {
- if (issuers != null && issuers.length != 0) {
- // check that certificate was issued by specified issuer
- loop: for (int ii = 0; ii < certs.length; ii++) {
- if (certs[ii] instanceof X509Certificate) {
- X500Principal issuer = ((X509Certificate) certs[ii])
- .getIssuerX500Principal();
- for (int iii = 0; iii < issuers.length; iii++) {
- if (issuer.equals(issuers[iii])) {
- found.add(alias);
- break loop;
- }
- }
- }
-
- }
- } else {
- found.add(alias);
- }
- }
- }
- }
- if (!found.isEmpty()) {
- return found.toArray(new String[found.size()]);
- }
- return null;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java
deleted file mode 100644
index c06aa7e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Logger.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.PrintStream;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
-/**
- * This class provides debug logging for JSSE provider implementation
- * TODO: Use java.util.logging
- */
-public class Logger {
-
- public static class Stream extends PrintStream {
- private final String prefix;
- private static int indent = 0;
-
- public Stream(String name) {
- super(System.err);
- prefix = name + "["+Thread.currentThread().getName()+"] ";
- }
-
- @Override
- public void print(String msg) {
- for (int i=0; i<indent; i++) {
- super.print(" ");
- }
- super.print(msg);
- }
-
- public void newIndent() {
- indent ++;
- }
-
- public void endIndent() {
- indent --;
- }
-
- @Override
- public void println(String msg) {
- print(prefix);
- super.println(msg);
- }
-
- public void print(byte[] data) {
- printAsHex(16, " ", "", data, 0, data.length);
- }
-
- public void print(byte[] data, int offset, int len) {
- printAsHex(16, " ", "", data, offset, len);
- }
-
- public void printAsHex(int perLine,
- String prefix,
- String delimiter,
- byte[] data) {
- printAsHex(perLine, prefix, delimiter, data, 0, data.length);
- }
-
- public void printAsHex(int perLine,
- String prefix,
- String delimiter,
- byte[] data, int offset, int len) {
- String line = "";
- for (int i=0; i<len; i++) {
- String tail =
- Integer.toHexString(0x00ff & data[i+offset]).toUpperCase();
- if (tail.length() == 1) {
- tail = "0" + tail;
- }
- line += prefix + tail + delimiter;
-
- if (((i+1)%perLine) == 0) {
- super.println(line);
- line = "";
- }
- }
- super.println(line);
- }
- }
-
- private static String[] names;
-
- static {
- try {
- names = AccessController
- .doPrivileged(new PrivilegedAction<String[]>() {
- public String[] run() {
- return System.getProperty("jsse", "").split(",");
- }
- });
- } catch (Exception e) {
- names = new String[0];
- }
- }
-
- public static Stream getStream(String name) {
- for (int i=0; i<names.length; i++) {
- if (names[i].equals(name)) {
- return new Stream(name);
- }
- }
- return null;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Message.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Message.java
deleted file mode 100644
index f1b2515..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/Message.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-
-/**
- *
- * Base class for handshake messages
- */
-public abstract class Message {
-
- /*
- * Message length
- */
- protected int length;
-
- /**
- * Returns message type
- * @return
- */
- abstract int getType();
-
- /**
- * Returns message length
- * @return
- */
- public int length() {
- return length;
- }
-
- /**
- * Sends message
- * @param out
- */
- abstract void send(HandshakeIODataStream out);
-
- /**
- * Sends fatal alert
- * @param description
- * @param reason
- */
- protected void fatalAlert(byte description, String reason) {
- throw new AlertException(description, new SSLHandshakeException(reason));
- }
-
- /**
- * Sends fatal alert
- * @param description
- * @param reason
- * @param cause
- */
- protected void fatalAlert(byte description, String reason, Throwable cause) {
- throw new AlertException(description, new SSLException(reason, cause));
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java
deleted file mode 100644
index 2220d36..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStreamWriter;
-import java.net.Socket;
-import java.security.PrivateKey;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-
-import org.bouncycastle.openssl.PEMWriter;
-
-/**
- * Provides the Java side of our JNI glue for OpenSSL. Currently only hashing
- * and verifying are covered. Is expected to grow over time. Also needs to move
- * into libcore/openssl at some point.
- */
-public class NativeCrypto {
-
- // --- OpenSSL library initialization --------------------------------------
- static {
- clinit();
- }
-
- private native static void clinit();
-
- // --- DSA/RSA public/private key handling functions -----------------------
-
- public static native int EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g, byte[] priv_key, byte[] pub_key);
-
- public static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q);
-
- public static native void EVP_PKEY_free(int pkey);
-
- // --- General context handling functions (despite the names) --------------
-
- public static native int EVP_new();
-
- public static native void EVP_free(int ctx);
-
- // --- Digest handling functions -------------------------------------------
-
- public static native void EVP_DigestInit(int ctx, String algorithm);
-
- public static native void EVP_DigestUpdate(int ctx, byte[] buffer, int offset, int length);
-
- public static native int EVP_DigestFinal(int ctx, byte[] hash, int offset);
-
- public static native int EVP_DigestSize(int ctx);
-
- public static native int EVP_DigestBlockSize(int ctx);
-
- // --- Signature handling functions ----------------------------------------
-
- public static native void EVP_VerifyInit(int ctx, String algorithm);
-
- public static native void EVP_VerifyUpdate(int ctx, byte[] buffer, int offset, int length);
-
- public static native int EVP_VerifyFinal(int ctx, byte[] signature, int offset, int length, int key);
-
- // --- SSL handling --------------------------------------------------------
-
- private static final String SUPPORTED_PROTOCOL_SSLV3 = "SSLv3";
- private static final String SUPPORTED_PROTOCOL_TLSV1 = "TLSv1";
-
- // SSL mode
- public static long SSL_MODE_HANDSHAKE_CUTTHROUGH = 0x00000040L;
-
- // SSL options
- public static long SSL_OP_NO_SSLv3 = 0x02000000L;
- public static long SSL_OP_NO_TLSv1 = 0x04000000L;
-
- public static native int SSL_CTX_new();
-
- public static native String[] SSL_CTX_get_ciphers(int ssl_ctx);
-
- public static String[] getDefaultCipherSuites() {
- int ssl_ctx = SSL_CTX_new();
- String[] supportedCiphers = SSL_CTX_get_ciphers(ssl_ctx);
- SSL_CTX_free(ssl_ctx);
- return supportedCiphers;
- }
-
- public static String[] getSupportedCipherSuites() {
- // TODO really return full cipher list
- return getDefaultCipherSuites();
- }
-
- public static native void SSL_CTX_free(int ssl_ctx);
-
- public static native int SSL_new(int ssl_ctx, String privatekey, String certificate, byte[] seed) throws IOException;
-
- /**
- * Initialize the SSL socket and set the certificates for the
- * future handshaking.
- */
- public static int SSL_new(SSLParameters sslParameters) throws IOException {
- boolean client = sslParameters.getUseClientMode();
-
- final int ssl_ctx = (client) ?
- sslParameters.getClientSessionContext().sslCtxNativePointer :
- sslParameters.getServerSessionContext().sslCtxNativePointer;
-
- // TODO support more than RSA certificates? non-openssl
- // SSLEngine implementation did these callbacks during
- // handshake after selecting cipher suite, not before
- // handshake. Should do the same via SSL_CTX_set_client_cert_cb
- final String alias = (client) ?
- sslParameters.getKeyManager().chooseClientAlias(new String[] { "RSA" }, null, null) :
- sslParameters.getKeyManager().chooseServerAlias("RSA", null, null);
-
- final String privateKeyString;
- final String certificateString;
- if (alias == null) {
- privateKeyString = null;
- certificateString = null;
- } else {
- PrivateKey privateKey = sslParameters.getKeyManager().getPrivateKey(alias);
- X509Certificate[] certificates = sslParameters.getKeyManager().getCertificateChain(alias);
-
- ByteArrayOutputStream privateKeyOS = new ByteArrayOutputStream();
- PEMWriter privateKeyPEMWriter = new PEMWriter(new OutputStreamWriter(privateKeyOS));
- privateKeyPEMWriter.writeObject(privateKey);
- privateKeyPEMWriter.close();
- privateKeyString = privateKeyOS.toString();
-
- ByteArrayOutputStream certificateOS = new ByteArrayOutputStream();
- PEMWriter certificateWriter = new PEMWriter(new OutputStreamWriter(certificateOS));
-
- for (X509Certificate certificate : certificates) {
- certificateWriter.writeObject(certificate);
- }
- certificateWriter.close();
- certificateString = certificateOS.toString();
- }
-
- final byte[] seed = (sslParameters.getSecureRandomMember() != null) ?
- sslParameters.getSecureRandomMember().generateSeed(1024) :
- null;
-
- return SSL_new(ssl_ctx,
- privateKeyString,
- certificateString,
- seed);
- }
-
-
- public static native long SSL_get_mode(int ssl);
-
- public static native long SSL_set_mode(int ssl, long options);
-
- public static native long SSL_clear_mode(int ssl, long options);
-
- public static native long SSL_get_options(int ssl);
-
- public static native long SSL_set_options(int ssl, long options);
-
- public static native long SSL_clear_options(int ssl, long options);
-
- public static String[] getSupportedProtocols() {
- return new String[] { SUPPORTED_PROTOCOL_SSLV3, SUPPORTED_PROTOCOL_TLSV1 };
- }
-
- public static String[] getEnabledProtocols(int ssl) {
- long options = SSL_get_options(ssl);
- ArrayList<String> array = new ArrayList<String>();
- if ((options & NativeCrypto.SSL_OP_NO_SSLv3) == 0) {
- array.add(SUPPORTED_PROTOCOL_SSLV3);
- }
- if ((options & NativeCrypto.SSL_OP_NO_TLSv1) == 0) {
- array.add(SUPPORTED_PROTOCOL_TLSV1);
- }
- return array.toArray(new String[array.size()]);
- }
-
- public static void setEnabledProtocols(int ssl, String[] protocols) {
- if (protocols == null) {
- throw new IllegalArgumentException("protocols == null");
- }
-
- // openssl uses negative logic letting you disable protocols.
- // so first, assume we need to set all (disable all ) and clear none (enable none).
- // in the loop, selectively move bits from set to clear (from disable to enable)
- long optionsToSet = (SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1);
- long optionsToClear = 0;
- for (int i = 0; i < protocols.length; i++) {
- String protocol = protocols[i];
- if (protocol == null) {
- throw new IllegalArgumentException("protocols[" + i + "] == null");
- }
- if (protocol.equals(SUPPORTED_PROTOCOL_SSLV3)) {
- optionsToSet &= ~SSL_OP_NO_SSLv3;
- optionsToClear |= SSL_OP_NO_SSLv3;
- } else if (protocol.equals(SUPPORTED_PROTOCOL_TLSV1)) {
- optionsToSet &= ~SSL_OP_NO_TLSv1;
- optionsToClear |= SSL_OP_NO_TLSv1;
- } else {
- throw new IllegalArgumentException("Protocol " + protocol +
- " is not supported");
- }
- }
-
- SSL_set_options(ssl, optionsToSet);
- SSL_clear_options(ssl, optionsToClear);
- }
-
- public static String[] checkEnabledProtocols(String[] protocols) {
- if (protocols == null) {
- throw new IllegalArgumentException("protocols parameter is null");
- }
- for (int i = 0; i < protocols.length; i++) {
- String protocol = protocols[i];
- if (protocol == null) {
- throw new IllegalArgumentException("protocols[" + i + "] == null");
- }
- if ((!protocol.equals(SUPPORTED_PROTOCOL_SSLV3))
- && (!protocol.equals(SUPPORTED_PROTOCOL_TLSV1))) {
- throw new IllegalArgumentException("Protocol " + protocol +
- " is not supported");
- }
- }
- return protocols;
- }
-
- public static native String[] SSL_get_ciphers(int ssl);
-
- public static native void SSL_set_cipher_list(int ssl, String ciphers);
-
- public static void setEnabledCipherSuites(int ssl, String[] cipherSuites) {
- checkEnabledCipherSuites(cipherSuites);
- String controlString = "";
- for (int i = 0; i < cipherSuites.length; i++) {
- String cipherSuite = cipherSuites[i];
- if (i == 0) {
- controlString = cipherSuite;
- } else {
- controlString += ":" + cipherSuite;
- }
- }
- SSL_set_cipher_list(ssl, controlString);
- }
-
- public static String[] checkEnabledCipherSuites(String[] cipherSuites) {
- if (cipherSuites == null) {
- throw new IllegalArgumentException("cipherSuites == null");
- }
- // makes sure all suites are valid, throwing on error
- String[] supportedCipherSuites = getSupportedCipherSuites();
- for (int i = 0; i < cipherSuites.length; i++) {
- String cipherSuite = cipherSuites[i];
- if (cipherSuite == null) {
- throw new IllegalArgumentException("cipherSuites[" + i + "] == null");
- }
- findSuite(supportedCipherSuites, cipherSuite);
- }
- return cipherSuites;
- }
-
- private static void findSuite(String[] supportedCipherSuites, String suite) {
- for (String supportedCipherSuite : supportedCipherSuites) {
- if (supportedCipherSuite.equals(suite)) {
- return;
- }
- }
- throw new IllegalArgumentException("Protocol " + suite + " is not supported.");
- }
-
- /*
- * See the OpenSSL ssl.h header file for more information.
- */
- public static final int SSL_VERIFY_NONE = 0x00;
- public static final int SSL_VERIFY_PEER = 0x01;
- public static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 0x02;
- public static final int SSL_VERIFY_CLIENT_ONCE = 0x04;
-
- public static native void SSL_set_verify(int sslNativePointer, int mode) throws IOException;
-
- public static native void SSL_set_session(int sslNativePointer, int sslSessionNativePointer) throws IOException;
-
- public static native void SSL_set_session_creation_enabled(int sslNativePointer, boolean creationEnabled) throws IOException;
-
- /**
- * Returns the sslSessionNativePointer of the negotiated session
- */
- public static native int SSL_do_handshake(int sslNativePointer, Socket sock,
- CertificateChainVerifier ccv, HandshakeCompletedCallback hcc,
- int timeout, boolean client_mode) throws IOException, CertificateException;
-
- public static native byte[][] SSL_get_certificate(int sslNativePointer);
-
- public static native void SSL_free(int sslNativePointer);
-
- public interface CertificateChainVerifier {
- /**
- * Verify that we trust the certificate chain is trusted.
- *
- * @param bytes An array of certficates in PEM encode bytes
- * @param authMethod auth algorithm name
- *
- * @throws CertificateException if the certificate is untrusted
- */
- public void verifyCertificateChain(byte[][] bytes, String authMethod) throws CertificateException;
- }
-
- public interface HandshakeCompletedCallback {
- /**
- * Called when SSL handshake is completed. Note that this can
- * be after SSL_do_handshake returns when handshake cutthrough
- * is enabled.
- */
- public void handshakeCompleted();
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigest.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigest.java
deleted file mode 100644
index 919d9e1..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigest.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.bouncycastle.crypto.ExtendedDigest;
-
-import java.security.NoSuchAlgorithmException;
-
-/**
- * Implements the BouncyCastle Digest interface using OpenSSL's EVP API.
- */
-public class OpenSSLMessageDigest implements ExtendedDigest {
-
- /**
- * Holds the name of the hashing algorithm, e.g. "SHA-1";
- */
- private String algorithm;
-
- /**
- * Holds a pointer to the native message digest context.
- */
- private int ctx;
-
- /**
- * Holds a dummy buffer for writing single bytes to the digest.
- */
- private byte[] singleByte = new byte[1];
-
- /**
- * Creates a new OpenSSLMessageDigest instance for the given algorithm
- * name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- *
- * @return The new OpenSSLMessageDigest instance.
- *
- * @throws RuntimeException In case of problems.
- */
- public static OpenSSLMessageDigest getInstance(String algorithm) {
- return new OpenSSLMessageDigest(algorithm);
- }
-
- /**
- * Creates a new OpenSSLMessageDigest instance for the given algorithm
- * name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- */
- private OpenSSLMessageDigest(String algorithm) {
- this.algorithm = algorithm;
-
- // We don't support MD2 anymore. This needs to also check for aliases
- // and OIDs.
- if ("MD2".equalsIgnoreCase(algorithm) || "1.2.840.113549.2.2"
- .equalsIgnoreCase(algorithm)) {
- throw new RuntimeException(algorithm + " not supported");
- }
-
- ctx = NativeCrypto.EVP_new();
- try {
- NativeCrypto.EVP_DigestInit(ctx, algorithm.replace("-", "").toLowerCase());
- } catch (Exception ex) {
- throw new RuntimeException(ex.getMessage() + " (" + algorithm + ")");
- }
- }
-
- public int doFinal(byte[] out, int outOff) {
- int i = NativeCrypto.EVP_DigestFinal(ctx, out, outOff);
- reset();
- return i;
- }
-
- public String getAlgorithmName() {
- return algorithm;
- }
-
- public int getDigestSize() {
- return NativeCrypto.EVP_DigestSize(ctx);
- }
-
- public int getByteLength() {
- return NativeCrypto.EVP_DigestBlockSize(ctx);
- }
-
- public void reset() {
- NativeCrypto.EVP_DigestInit(ctx, algorithm.replace("-", "").toLowerCase());
- }
-
- public void update(byte in) {
- singleByte[0] = in;
- NativeCrypto.EVP_DigestUpdate(ctx, singleByte, 0, 1);
- }
-
- public void update(byte[] in, int inOff, int len) {
- NativeCrypto.EVP_DigestUpdate(ctx, in, inOff, len);
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- NativeCrypto.EVP_free(ctx);
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK.java
deleted file mode 100644
index 4ba3a74..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLMessageDigestJDK.java
+++ /dev/null
@@ -1,117 +0,0 @@
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-
-/**
- * Implements the JDK MessageDigest interface using OpenSSL's EVP API.
- */
-public class OpenSSLMessageDigestJDK extends MessageDigest {
-
- /**
- * Holds a pointer to the native message digest context.
- */
- private int ctx;
-
- /**
- * Holds a dummy buffer for writing single bytes to the digest.
- */
- private byte[] singleByte = new byte[1];
-
- /**
- * Creates a new OpenSSLMessageDigestJDK instance for the given algorithm
- * name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- *
- * @return The new OpenSSLMessageDigestJDK instance.
- *
- * @throws RuntimeException In case of problems.
- */
- public static OpenSSLMessageDigestJDK getInstance(String algorithm) throws NoSuchAlgorithmException{
- return new OpenSSLMessageDigestJDK(algorithm);
- }
-
- /**
- * Creates a new OpenSSLMessageDigest instance for the given algorithm
- * name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- */
- private OpenSSLMessageDigestJDK(String algorithm) throws NoSuchAlgorithmException {
- super(algorithm);
-
- // We don't support MD2 anymore. This needs to also check for aliases
- // and OIDs.
- if ("MD2".equalsIgnoreCase(algorithm) || "1.2.840.113549.2.2"
- .equalsIgnoreCase(algorithm)) {
- throw new NoSuchAlgorithmException(algorithm);
- }
-
- ctx = NativeCrypto.EVP_new();
- try {
- NativeCrypto.EVP_DigestInit(ctx, getAlgorithm().replace("-", "").toLowerCase());
- } catch (Exception ex) {
- throw new NoSuchAlgorithmException(ex.getMessage() + " (" + algorithm + ")");
- }
- }
-
- @Override
- protected byte[] engineDigest() {
- byte[] result = new byte[NativeCrypto.EVP_DigestSize(ctx)];
- NativeCrypto.EVP_DigestFinal(ctx, result, 0);
- engineReset();
- return result;
- }
-
- @Override
- protected void engineReset() {
- NativeCrypto.EVP_DigestInit(ctx, getAlgorithm().replace("-", "").toLowerCase());
- }
-
- @Override
- protected int engineGetDigestLength() {
- return NativeCrypto.EVP_DigestSize(ctx);
- }
-
- @Override
- protected void engineUpdate(byte input) {
- singleByte[0] = input;
- engineUpdate(singleByte, 0, 1);
- }
-
- @Override
- protected void engineUpdate(byte[] input, int offset, int len) {
- NativeCrypto.EVP_DigestUpdate(ctx, input, offset, len);
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- NativeCrypto.EVP_free(ctx);
- }
-
- static public class MD5 extends OpenSSLMessageDigestJDK {
- public MD5() throws NoSuchAlgorithmException {
- super("MD5");
- }
- }
-
- static public class SHA1 extends OpenSSLMessageDigestJDK {
- public SHA1() throws NoSuchAlgorithmException {
- super("SHA-1");
- }
- }
-
- static public class SHA224 extends OpenSSLMessageDigestJDK {
- public SHA224() throws NoSuchAlgorithmException {
- super("SHA-224");
- }
- }
-
- static public class SHA256 extends OpenSSLMessageDigestJDK {
- public SHA256() throws NoSuchAlgorithmException {
- super("SHA-256");
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketFactoryImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketFactoryImpl.java
deleted file mode 100644
index f342457..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketFactoryImpl.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.ServerSocket;
-import java.security.KeyManagementException;
-
-public class OpenSSLServerSocketFactoryImpl extends javax.net.ssl.SSLServerSocketFactory {
-
- private SSLParameters sslParameters;
- private IOException instantiationException;
-
- public OpenSSLServerSocketFactoryImpl() {
- super();
- try {
- this.sslParameters = SSLParameters.getDefault();
- this.sslParameters.setUseClientMode(false);
- } catch (KeyManagementException e) {
- instantiationException =
- new IOException("Delayed instantiation exception:");
- instantiationException.initCause(e);
- }
- }
-
- public OpenSSLServerSocketFactoryImpl(SSLParameters sslParameters) {
- this.sslParameters = (SSLParameters) sslParameters.clone();
- this.sslParameters.setUseClientMode(false);
- }
-
- public String[] getDefaultCipherSuites() {
- return NativeCrypto.getDefaultCipherSuites();
- }
-
- public String[] getSupportedCipherSuites() {
- return NativeCrypto.getSupportedCipherSuites();
- }
-
- public ServerSocket createServerSocket() throws IOException {
- return new OpenSSLServerSocketImpl((SSLParameters) sslParameters.clone());
- }
-
- public ServerSocket createServerSocket(int port) throws IOException {
- return new OpenSSLServerSocketImpl(port, (SSLParameters) sslParameters.clone());
- }
-
- public ServerSocket createServerSocket(int port, int backlog)
- throws IOException {
- return new OpenSSLServerSocketImpl(port, backlog, (SSLParameters) sslParameters.clone());
- }
-
- public ServerSocket createServerSocket(int port, int backlog,
- InetAddress iAddress) throws IOException {
- return new OpenSSLServerSocketImpl(port, backlog, iAddress, (SSLParameters) sslParameters.clone());
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketImpl.java
deleted file mode 100644
index 8d5a43e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLServerSocketImpl.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-
-/**
- * OpenSSL-based implementation of server sockets.
- *
- * This class only supports SSLv3 and TLSv1. This should be documented elsewhere
- * later, for example in the package.html or a separate reference document.
- */
-public class OpenSSLServerSocketImpl extends javax.net.ssl.SSLServerSocket {
- private final SSLParameters sslParameters;
- private String[] enabledProtocols = NativeCrypto.getSupportedProtocols();
- private String[] enabledCipherSuites = NativeCrypto.getDefaultCipherSuites();
-
- protected OpenSSLServerSocketImpl(SSLParameters sslParameters)
- throws IOException {
- super();
- this.sslParameters = sslParameters;
- }
-
- protected OpenSSLServerSocketImpl(int port, SSLParameters sslParameters)
- throws IOException {
- super(port);
- this.sslParameters = sslParameters;
- }
-
- protected OpenSSLServerSocketImpl(int port, int backlog, SSLParameters sslParameters)
- throws IOException {
- super(port, backlog);
- this.sslParameters = sslParameters;
- }
-
- protected OpenSSLServerSocketImpl(int port, int backlog, InetAddress iAddress, SSLParameters sslParameters)
- throws IOException {
- super(port, backlog, iAddress);
- this.sslParameters = sslParameters;
- }
-
- @Override
- public boolean getEnableSessionCreation() {
- return sslParameters.getEnableSessionCreation();
- }
-
- @Override
- public void setEnableSessionCreation(boolean flag) {
- sslParameters.setEnableSessionCreation(flag);
- }
-
- /**
- * The names of the protocols' versions that may be used on this SSL
- * connection.
- * @return an array of protocols names
- */
- @Override
- public String[] getSupportedProtocols() {
- return NativeCrypto.getSupportedProtocols();
- }
-
- /**
- * The names of the protocols' versions that in use on this SSL connection.
- *
- * @return an array of protocols names
- */
- @Override
- public String[] getEnabledProtocols() {
- return enabledProtocols.clone();
- }
-
- /**
- * This method enables the protocols' versions listed by
- * getSupportedProtocols().
- *
- * @param protocols names of all the protocols to enable.
- *
- * @throws IllegalArgumentException when one or more of the names in the
- * array are not supported, or when the array is null.
- */
- @Override
- public void setEnabledProtocols(String[] protocols) {
- enabledProtocols = NativeCrypto.checkEnabledProtocols(protocols);
- }
-
- @Override
- public String[] getSupportedCipherSuites() {
- return NativeCrypto.getSupportedCipherSuites();
- }
-
- @Override
- public String[] getEnabledCipherSuites() {
- return enabledCipherSuites.clone();
- }
-
- /**
- * This method enables the cipher suites listed by
- * getSupportedCipherSuites().
- *
- * @param suites the names of all the cipher suites to enable
- * @throws IllegalArgumentException when one or more of the ciphers in array
- * suites are not supported, or when the array is null.
- */
- @Override
- public void setEnabledCipherSuites(String[] suites) {
- enabledCipherSuites = NativeCrypto.checkEnabledCipherSuites(suites);
- }
-
- @Override
- public boolean getWantClientAuth() {
- return sslParameters.getWantClientAuth();
- }
-
- @Override
- public void setWantClientAuth(boolean want) {
- sslParameters.setWantClientAuth(want);
- }
-
- @Override
- public boolean getNeedClientAuth() {
- return sslParameters.getNeedClientAuth();
- }
-
- @Override
- public void setNeedClientAuth(boolean need) {
- sslParameters.setNeedClientAuth(need);
- }
-
- @Override
- public void setUseClientMode(boolean mode) {
- sslParameters.setUseClientMode(mode);
- }
-
- @Override
- public boolean getUseClientMode() {
- return sslParameters.getUseClientMode();
- }
-
- @Override
- public Socket accept() throws IOException {
- OpenSSLSocketImpl socket = new OpenSSLSocketImpl(sslParameters,
- enabledProtocols.clone(),
- enabledCipherSuites.clone());
- implAccept(socket);
- return socket;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java
deleted file mode 100644
index f42bcae..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSessionImpl.java
+++ /dev/null
@@ -1,483 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.Principal;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import java.util.Iterator;
-import java.util.UnknownFormatConversionException;
-import java.util.Vector;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLPermission;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.net.ssl.SSLSessionBindingListener;
-import javax.net.ssl.SSLSessionContext;
-import javax.security.cert.CertificateEncodingException;
-
-import org.apache.harmony.luni.util.TwoKeyHashMap;
-import org.apache.harmony.security.provider.cert.X509CertImpl;
-
-/**
- * Implementation of the class OpenSSLSessionImpl
- * based on OpenSSL. The JNI native interface for some methods
- * of this this class are defined in the file:
- * org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
- */
-public class OpenSSLSessionImpl implements SSLSession {
-
- long lastAccessedTime = 0;
- X509Certificate[] localCertificates;
- X509Certificate[] peerCertificates;
-
- private boolean isValid = true;
- private TwoKeyHashMap values = new TwoKeyHashMap();
- private javax.security.cert.X509Certificate[] peerCertificateChain;
- protected int sslSessionNativePointer;
- private String peerHost;
- private int peerPort;
- private AbstractSessionContext sessionContext;
- private byte[] id;
-
- /**
- * Class constructor creates an SSL session context given the appropriate
- * SSL parameters.
- *
- * @param session the Identifier for SSL session
- * @param sslParameters the SSL parameters like ciphers' suites etc.
- */
- protected OpenSSLSessionImpl(int sslSessionNativePointer, X509Certificate[] localCertificates,
- String peerHost, int peerPort, AbstractSessionContext sessionContext) {
- this.sslSessionNativePointer = sslSessionNativePointer;
- this.localCertificates = localCertificates;
- this.peerHost = peerHost;
- this.peerPort = peerPort;
- this.sessionContext = sessionContext;
- }
-
- /**
- * Constructs a session from a byte[] containing DER data. This
- * allows loading the saved session.
- * @throws IOException
- */
- OpenSSLSessionImpl(byte[] derData,
- String peerHost, int peerPort,
- javax.security.cert.X509Certificate[] peerCertificateChain,
- AbstractSessionContext sessionContext)
- throws IOException {
- this(initializeNativeImpl(derData, derData.length),
- null,
- peerHost,
- peerPort,
- sessionContext);
- this.peerCertificateChain = peerCertificateChain;
- // TODO move this check into native code so we can throw an error with more information
- if (this.sslSessionNativePointer == 0) {
- throw new IOException("Invalid session data");
- }
- }
-
- private static native int initializeNativeImpl(byte[] data, int size);
-
- /**
- * Gets the identifier of the actual SSL session
- * @return array of sessions' identifiers.
- */
- public byte[] getId() {
- if (id == null) {
- resetId();
- }
- return id;
- }
-
- public static native byte[] getId(int sslSessionNativePointer);
-
- void resetId() {
- id = getId(sslSessionNativePointer);
- }
-
- /**
- * Get the session object in DER format. This allows saving the session
- * data or sharing it with other processes.
- */
- byte[] getEncoded() {
- return getEncoded(sslSessionNativePointer);
- }
-
- private native static byte[] getEncoded(int sslSessionNativePointer);
-
- /**
- * Gets the creation time of the SSL session.
- * @return the session's creation time in milliseconds since the epoch
- */
- public long getCreationTime() {
- return getCreationTime(sslSessionNativePointer);
- }
-
- private static native long getCreationTime(int sslSessionNativePointer);
-
- /**
- * Gives the last time this concrete SSL session was accessed. Accessing
- * here is to mean that a new connection with the same SSL context data was
- * established.
- *
- * @return the session's last access time in milliseconds since the epoch
- */
- public long getLastAccessedTime() {
- return (lastAccessedTime == 0) ? getCreationTime() : lastAccessedTime;
- }
-
- /**
- * Gives the largest buffer size for the application's data bound to this
- * concrete SSL session.
- * @return the largest buffer size
- */
- public int getApplicationBufferSize() {
- return SSLRecordProtocol.MAX_DATA_LENGTH;
- }
-
- /**
- * Gives the largest SSL/TLS packet size one can expect for this concrete
- * SSL session.
- * @return the largest packet size
- */
- public int getPacketBufferSize() {
- return SSLRecordProtocol.MAX_SSL_PACKET_SIZE;
- }
-
- /**
- * Gives the principal (subject) of this concrete SSL session used in the
- * handshaking phase of the connection.
- * @return a X509 certificate or null if no principal was defined
- */
- public Principal getLocalPrincipal() {
- if (localCertificates != null && localCertificates.length > 0) {
- return localCertificates[0].getSubjectX500Principal();
- } else {
- return null;
- }
- }
-
- /**
- * Gives the certificate(s) of the principal (subject) of this concrete SSL
- * session used in the handshaking phase of the connection. The OpenSSL
- * native method supports only RSA certificates.
- * @return an array of certificates (the local one first and then eventually
- * that of the certification authority) or null if no certificate
- * were used during the handshaking phase.
- */
- public Certificate[] getLocalCertificates() {
- return localCertificates;
- }
-
- /**
- * Returns the X509 certificates of the peer in the PEM format.
- */
- private static native byte[][] getPeerCertificatesImpl(int sslCtxNativePointer,
- int sslSessionNativePointer);
-
- /**
- * Gives the certificate(s) of the peer in this SSL session
- * used in the handshaking phase of the connection.
- * Please notice hat this method is superseded by
- * <code>getPeerCertificates()</code>.
- * @return an array of X509 certificates (the peer's one first and then
- * eventually that of the certification authority) or null if no
- * certificate were used during the SSL connection.
- * @throws <code>SSLPeerUnverifiedCertificateException</code> if either a
- * not X509 certificate was used (i.e. Kerberos certificates) or the
- * peer could not be verified.
- */
- public javax.security.cert.X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException {
- if (peerCertificateChain == null) {
- try {
- byte[][] bytes = getPeerCertificatesImpl(sessionContext.sslCtxNativePointer, sslSessionNativePointer);
- if (bytes == null) throw new SSLPeerUnverifiedException("No certificate available");
-
- peerCertificateChain = new javax.security.cert.X509Certificate[bytes.length];
-
- for(int i = 0; i < bytes.length; i++) {
- peerCertificateChain[i] = javax.security.cert.X509Certificate.getInstance(bytes[i]);
- }
-
- return peerCertificateChain;
- } catch (javax.security.cert.CertificateException e) {
- throw new SSLPeerUnverifiedException(e.getMessage());
- }
- } else {
- return peerCertificateChain;
- }
- }
-
- /**
- * Gives the identitity of the peer in this SSL session
- * determined via certificate(s).
- * @return an array of X509 certificates (the peer's one first and then
- * eventually that of the certification authority) or null if no
- * certificate were used during the SSL connection.
- * @throws <code>SSLPeerUnverifiedException</code> if either a not X509
- * certificate was used (i.e. Kerberos certificates) or the peer
- * could not be verified.
- */
- public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
- if (peerCertificates == null) {
- if (peerCertificateChain == null) getPeerCertificateChain();
- try {
- if (peerCertificateChain.length == 0) return new X509Certificate[]{};
-
- peerCertificates = new X509CertImpl[peerCertificateChain.length];
- for(int i = 0; i < peerCertificates.length; i++) {
- peerCertificates[i] = new X509CertImpl(peerCertificateChain[i].getEncoded());
- }
- return peerCertificates;
- } catch (SSLPeerUnverifiedException e) {
- return new X509Certificate[]{};
- } catch (IOException e) {
- return new X509Certificate[]{};
- } catch (CertificateEncodingException e) {
- return new X509Certificate[]{};
- }
- } else {
- return peerCertificates;
- }
- }
-
- /**
- * The identity of the principal that was used by the peer during the SSL
- * handshake phase is returned by this method.
- * @return a X500Principal of the last certificate for X509-based
- * cipher suites. If no principal was sent, then null is returned.
- * @throws <code>SSLPeerUnverifiedException</code> if either a not X509
- * certificate was used (i.e. Kerberos certificates) or the
- * peer does not exist.
- *
- */
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- getPeerCertificates();
- if (peerCertificates == null) {
- throw new SSLPeerUnverifiedException("No peer certificate");
- }
- return peerCertificates[0].getSubjectX500Principal();
- }
-
- /**
- * The peer's host name used in this SSL session is returned. It is the host
- * name of the client for the server; and that of the server for the client.
- * It is not a reliable way to get a fully qualified host name: it is mainly
- * used internally to implement links for a temporary cache of SSL sessions.
- *
- * @return the host name of the peer, or null if no information is
- * available.
- *
- */
- public String getPeerHost() {
- return peerHost;
- }
-
- /**
- * Gives the peer's port number for the actual SSL session. It is the port
- * number of the client for the server; and that of the server for the
- * client. It is not a reliable way to get a peer's port number: it is
- * mainly used internally to implement links for a temporary cache of SSL
- * sessions.
- * @return the peer's port number, or -1 if no one is available.
- *
- */
- public int getPeerPort() {
- return peerPort;
- }
-
- /**
- * Gives back a string identifier of the crypto tools used in the actual SSL
- * session. For example AES_256_WITH_MD5.
- *
- * @return an identifier for all the cryptographic algorithms used in the
- * actual SSL session.
- */
- public String getCipherSuite() {
- return getCipherSuite(sslSessionNativePointer);
- }
-
- private static native String getCipherSuite(int sslSessionNativePointer);
-
- /**
- * Gives back the standard version name of the SSL protocol used in all
- * connections pertaining to this SSL session.
- *
- * @return the standard version name of the SSL protocol used in all
- * connections pertaining to this SSL session.
- *
- */
- public String getProtocol() {
- return getProtocol(sslSessionNativePointer);
- }
-
- private static native String getProtocol(int sslSessionNativePointer);
-
- /**
- * Gives back the context to which the actual SSL session is bound. A SSL
- * context consists of (1) a possible delegate, (2) a provider and (3) a
- * protocol. If the security manager is activated and one tries to access
- * the SSL context an exception may be thrown if a
- * <code>SSLPermission("getSSLSessionContext")</code>
- * permission is not set.
- * @return the SSL context used for this session, or null if it is
- * unavailable.
- */
- public SSLSessionContext getSessionContext() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new SSLPermission("getSSLSessionContext"));
- }
- return sessionContext;
- }
-
- /**
- * Gives back a boolean flag signaling whether a SSL session is valid and
- * available
- * for resuming or joining or not.
- * @return true if this session may be resumed.
- */
- public boolean isValid() {
- SSLSessionContext context = sessionContext;
- if (isValid
- && context != null
- && context.getSessionTimeout() != 0
- && lastAccessedTime + context.getSessionTimeout() > System.currentTimeMillis()) {
- isValid = false;
- }
- return isValid;
- }
-
- /**
- * It invalidates a SSL session forbidding any resumption.
- */
- public void invalidate() {
- isValid = false;
- sessionContext = null;
- }
-
- /**
- * Gives back the object which is bound to the the input parameter name.
- * This name is a sort of link to the data of the SSL session's application
- * layer, if any exists. The search for this link is monitored, as a matter
- * of security, by the full machinery of the <code>AccessController</code>
- * class.
- *
- * @param name the name of the binding to find.
- * @return the value bound to that name, or null if the binding does not
- * exist.
- * @throws <code>IllegalArgumentException</code> if the argument is null.
- */
- public Object getValue(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- return values.get(name, AccessController.getContext());
- }
-
- /**
- * Gives back an array with the names (sort of links) of all the data
- * objects of the application layer bound into the SSL session. The search
- * for this link is monitored, as a matter of security, by the full
- * machinery of the <code>AccessController</code> class.
- *
- * @return a non-null (possibly empty) array of names of the data objects
- * bound to this SSL session.
- */
- public String[] getValueNames() {
- Vector v = new Vector();
- AccessControlContext current = AccessController.getContext();
- AccessControlContext cont;
- for (Iterator it = values.entrySet().iterator(); it.hasNext();) {
- TwoKeyHashMap.Entry entry = (TwoKeyHashMap.Entry) it.next();
- cont = (AccessControlContext) entry.getKey2();
- if ((current == null && cont == null)
- || (current != null && current.equals(cont))) {
- v.add(entry.getKey1());
- }
- }
- return (String[]) v.toArray(new String[0]);
- }
-
- /**
- * A link (name) with the specified value object of the SSL session's
- * application layer data is created or replaced. If the new (or existing)
- * value object implements the <code>SSLSessionBindingListener</code>
- * interface, that object will be notified in due course. These links-to
- * -data bounds are monitored, as a matter of security, by the full
- * machinery of the <code>AccessController</code> class.
- *
- * @param name the name of the link (no null are
- * accepted!)
- * @param value data object that shall be bound to
- * name.
- * @throws <code>IllegalArgumentException</code> if one or both
- * argument(s) is null.
- */
- public void putValue(String name, Object value) {
- if (name == null || value == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- Object old = values.put(name, AccessController.getContext(), value);
- if (value instanceof SSLSessionBindingListener) {
- ((SSLSessionBindingListener) value)
- .valueBound(new SSLSessionBindingEvent(this, name));
- }
- if (old instanceof SSLSessionBindingListener) {
- ((SSLSessionBindingListener) old)
- .valueUnbound(new SSLSessionBindingEvent(this, name));
- }
- }
-
- /**
- * Removes a link (name) with the specified value object of the SSL
- * session's application layer data.
- *
- * <p>If the value object implements the <code>SSLSessionBindingListener</code>
- * interface, the object will receive a <code>valueUnbound</code> notification.
- *
- * <p>These links-to -data bounds are
- * monitored, as a matter of security, by the full machinery of the
- * <code>AccessController</code> class.
- *
- * @param name the name of the link (no null are
- * accepted!)
- * @throws <code>IllegalArgumentException</code> if the argument is null.
- */
- public void removeValue(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- Object old = values.remove(name, AccessController.getContext());
- if (old instanceof SSLSessionBindingListener) {
- SSLSessionBindingListener listener = (SSLSessionBindingListener) old;
- listener.valueUnbound(new SSLSessionBindingEvent(this, name));
- }
- }
-
- protected void finalize() {
- freeImpl(sslSessionNativePointer);
- }
-
- public static native void freeImpl(int session);
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignature.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignature.java
deleted file mode 100644
index 3db6301..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSignature.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.InvalidKeyException;
-import java.security.InvalidParameterException;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PublicKey;
-import java.security.Signature;
-import java.security.SignatureException;
-import java.security.interfaces.DSAParams;
-import java.security.interfaces.DSAPublicKey;
-import java.security.interfaces.RSAPublicKey;
-
-/**
- * Implements the JDK MessageDigest interface using OpenSSL's EVP API.
- */
-public class OpenSSLSignature extends Signature {
-
- /**
- * Holds a pointer to the native message digest context.
- */
- private int ctx;
-
- /**
- * Holds a pointer to the native DSA key.
- */
- private int dsa;
-
- /**
- * Holds a pointer to the native RSA key.
- */
- private int rsa;
-
- /**
- * Holds the OpenSSL name of the algorithm (lower case, no dashes).
- */
- private String evpAlgorithm;
-
- /**
- * Holds a dummy buffer for writing single bytes to the digest.
- */
- private byte[] singleByte = new byte[1];
-
- /**
- * Creates a new OpenSSLSignature instance for the given algorithm name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- *
- * @return The new OpenSSLSignature instance.
- *
- * @throws RuntimeException In case of problems.
- */
- public static OpenSSLSignature getInstance(String algorithm) throws NoSuchAlgorithmException {
- //log("OpenSSLSignature", "getInstance() invoked with " + algorithm);
- return new OpenSSLSignature(algorithm);
- }
-
- /**
- * Creates a new OpenSSLSignature instance for the given algorithm name.
- *
- * @param algorithm The name of the algorithm, e.g. "SHA1".
- */
- private OpenSSLSignature(String algorithm) throws NoSuchAlgorithmException {
- super(algorithm);
-
- int i = algorithm.indexOf("with");
- if (i == -1) {
- throw new NoSuchAlgorithmException(algorithm);
- }
-
- // We don't support MD2 anymore. This needs to also check for aliases
- // and OIDs.
- if ("MD2withRSA".equalsIgnoreCase(algorithm) ||
- "MD2withRSAEncryption".equalsIgnoreCase(algorithm) ||
- "1.2.840.113549.1.1.2".equalsIgnoreCase(algorithm) ||
- "MD2/RSA".equalsIgnoreCase(algorithm)) {
- throw new NoSuchAlgorithmException("MD2withRSA");
- }
-
- // For the special combination of DSA and SHA1, we need to pass the
- // algorithm name as a pair consisting of crypto algorithm and hash
- // algorithm. For all other (RSA) cases, passing the hash algorithm
- // alone is not only sufficient, but actually necessary. OpenSSL
- // doesn't accept something like RSA-SHA1.
- if ("1.3.14.3.2.26with1.2.840.10040.4.1".equals(algorithm)
- || "SHA1withDSA".equals(algorithm)
- || "SHAwithDSA".equals(algorithm)) {
- evpAlgorithm = "DSA-SHA";
- } else {
- evpAlgorithm = algorithm.substring(0, i).replace("-", "").toUpperCase();
- }
-
- ctx = NativeCrypto.EVP_new();
- }
-
- @Override
- protected void engineUpdate(byte input) {
- singleByte[0] = input;
- engineUpdate(singleByte, 0, 1);
- }
-
- @Override
- protected void engineUpdate(byte[] input, int offset, int len) {
- if (state == SIGN) {
- throw new UnsupportedOperationException();
- } else {
- NativeCrypto.EVP_VerifyUpdate(ctx, input, offset, len);
- }
- }
-
- @Override
- protected Object engineGetParameter(String param) throws InvalidParameterException {
- return null;
- }
-
- @Override
- protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected void engineInitVerify(PublicKey publicKey) throws InvalidKeyException {
- //log("OpenSSLSignature", "engineInitVerify() invoked with " + publicKey.getClass().getCanonicalName());
-
- if (publicKey instanceof DSAPublicKey) {
- try {
- DSAPublicKey dsaPublicKey = (DSAPublicKey)publicKey;
- DSAParams dsaParams = dsaPublicKey.getParams();
- dsa = NativeCrypto.EVP_PKEY_new_DSA(dsaParams.getP().toByteArray(),
- dsaParams.getQ().toByteArray(), dsaParams.getG().toByteArray(),
- dsaPublicKey.getY().toByteArray(), null);
-
- } catch (Exception ex) {
- throw new InvalidKeyException(ex.toString());
- }
- } else if (publicKey instanceof RSAPublicKey) {
- try {
- RSAPublicKey rsaPublicKey = (RSAPublicKey)publicKey;
- rsa = NativeCrypto.EVP_PKEY_new_RSA(rsaPublicKey.getModulus().toByteArray(),
- rsaPublicKey.getPublicExponent().toByteArray(), null, null, null);
-
- } catch (Exception ex) {
- throw new InvalidKeyException(ex.toString());
- }
- } else {
- throw new InvalidKeyException("Need DSA or RSA public key");
- }
-
- try {
- NativeCrypto.EVP_VerifyInit(ctx, evpAlgorithm);
- } catch (Exception ex) {
- throw new RuntimeException(ex);
- }
- }
-
- @Override
- protected void engineSetParameter(String param, Object value) throws InvalidParameterException {
- }
-
- @Override
- protected byte[] engineSign() throws SignatureException {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected boolean engineVerify(byte[] sigBytes) throws SignatureException {
- int handle = (rsa != 0) ? rsa : dsa;
-
- if (handle == 0) {
- // This can't actually happen, but you never know...
- throw new SignatureException("Need DSA or RSA public key");
- }
-
- try {
- int result = NativeCrypto.EVP_VerifyFinal(ctx, sigBytes, 0, sigBytes.length, handle);
- return result == 1;
- } catch (Exception ex) {
- throw new SignatureException(ex);
- }
-
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
-
- if (dsa != 0) {
- NativeCrypto.EVP_PKEY_free(dsa);
- }
-
- if (rsa != 0) {
- NativeCrypto.EVP_PKEY_free(rsa);
- }
-
- if (ctx != 0) {
- NativeCrypto.EVP_free(ctx);
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java
deleted file mode 100644
index 7b6d7c8..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketFactoryImpl.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.UnknownHostException;
-import java.security.KeyManagementException;
-
-import org.apache.harmony.xnet.provider.jsse.SSLParameters;
-
-public class OpenSSLSocketFactoryImpl extends javax.net.ssl.SSLSocketFactory {
-
- private SSLParameters sslParameters;
- private IOException instantiationException;
-
- public OpenSSLSocketFactoryImpl() {
- super();
- try {
- sslParameters = SSLParameters.getDefault();
- } catch (KeyManagementException e) {
- instantiationException =
- new IOException("Delayed instantiation exception:");
- instantiationException.initCause(e);
- }
- }
-
- public OpenSSLSocketFactoryImpl(SSLParameters sslParameters) {
- super();
- this.sslParameters = sslParameters;
- }
-
- public String[] getDefaultCipherSuites() {
- return NativeCrypto.getDefaultCipherSuites();
- }
-
- public String[] getSupportedCipherSuites() {
- return NativeCrypto.getSupportedCipherSuites();
- }
-
- public Socket createSocket() throws IOException {
- if (instantiationException != null) {
- throw instantiationException;
- }
- return new OpenSSLSocketImpl((SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
- return new OpenSSLSocketImpl(host, port, (SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
- throws IOException, UnknownHostException {
- return new OpenSSLSocketImpl(host, port, localHost, localPort, (SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(InetAddress host, int port) throws IOException {
- return new OpenSSLSocketImpl(host, port, (SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort)
- throws IOException {
- return new OpenSSLSocketImpl(address, port, localAddress, localPort, (SSLParameters) sslParameters.clone());
- }
-
- public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
- return new OpenSSLSocketImplWrapper(s, host, port, autoClose, (SSLParameters) sslParameters.clone());
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java
deleted file mode 100644
index edef590..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java
+++ /dev/null
@@ -1,995 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-import java.net.SocketException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.RSAPublicKey;
-import java.util.ArrayList;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.net.ssl.HandshakeCompletedEvent;
-import javax.net.ssl.HandshakeCompletedListener;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLSession;
-
-import org.apache.harmony.security.provider.cert.X509CertImpl;
-
-/**
- * Implementation of the class OpenSSLSocketImpl
- * based on OpenSSL. The JNI native interface for some methods
- * of this this class are defined in the file:
- * org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp
- *
- * This class only supports SSLv3 and TLSv1. This should be documented elsewhere
- * later, for example in the package.html or a separate reference document.
- */
-public class OpenSSLSocketImpl
- extends javax.net.ssl.SSLSocket
- implements NativeCrypto.CertificateChainVerifier, NativeCrypto.HandshakeCompletedCallback {
- private int sslNativePointer;
- private InputStream is;
- private OutputStream os;
- private final Object handshakeLock = new Object();
- private final Object readLock = new Object();
- private final Object writeLock = new Object();
- private SSLParameters sslParameters;
- private String[] enabledProtocols;
- private String[] enabledCipherSuites;
- private OpenSSLSessionImpl sslSession;
- private Socket socket;
- private boolean autoClose;
- private boolean handshakeStarted = false;
-
- /**
- * Not set to true until the update from native that tells us the
- * full handshake is complete, since SSL_do_handshake can return
- * before the handshake is completely done due to
- * handshake_cutthrough support.
- */
- private boolean handshakeCompleted = false;
-
- private ArrayList<HandshakeCompletedListener> listeners;
- private int timeout = 0;
- // BEGIN android-added
- private int handshakeTimeout = -1; // -1 = same as timeout; 0 = infinite
- // END android-added
- private InetSocketAddress address;
-
- private static final AtomicInteger instanceCount = new AtomicInteger(0);
-
- public static int getInstanceCount() {
- return instanceCount.get();
- }
-
- private static void updateInstanceCount(int amount) {
- instanceCount.addAndGet(amount);
- }
-
- /**
- * Class constructor with 1 parameter
- *
- * @param sslParameters Parameters for the SSL
- * context
- * @throws IOException if network fails
- */
- protected OpenSSLSocketImpl(SSLParameters sslParameters) throws IOException {
- super();
- init(sslParameters);
- }
-
- /**
- * Create an OpenSSLSocketImpl from an OpenSSLServerSocketImpl
- *
- * @param sslParameters Parameters for the SSL
- * context
- * @throws IOException if network fails
- */
- protected OpenSSLSocketImpl(SSLParameters sslParameters,
- String[] enabledProtocols,
- String[] enabledCipherSuites) throws IOException {
- super();
- init(sslParameters, enabledProtocols, enabledCipherSuites);
- }
-
- /**
- * Class constructor with 3 parameters
- *
- * @throws IOException if network fails
- * @throws java.net.UnknownHostException host not defined
- */
- protected OpenSSLSocketImpl(String host, int port,
- SSLParameters sslParameters)
- throws IOException {
- super(host, port);
- init(sslParameters);
- }
-
- /**
- * Class constructor with 3 parameters: 1st is InetAddress
- *
- * @throws IOException if network fails
- * @throws java.net.UnknownHostException host not defined
- */
- protected OpenSSLSocketImpl(InetAddress address, int port,
- SSLParameters sslParameters)
- throws IOException {
- super(address, port);
- init(sslParameters);
- }
-
-
- /**
- * Class constructor with 5 parameters: 1st is host
- *
- * @throws IOException if network fails
- * @throws java.net.UnknownHostException host not defined
- */
- protected OpenSSLSocketImpl(String host, int port, InetAddress clientAddress,
- int clientPort, SSLParameters sslParameters)
- throws IOException {
- super(host, port, clientAddress, clientPort);
- init(sslParameters);
- }
-
- /**
- * Class constructor with 5 parameters: 1st is InetAddress
- *
- * @throws IOException if network fails
- * @throws java.net.UnknownHostException host not defined
- */
- protected OpenSSLSocketImpl(InetAddress address, int port,
- InetAddress clientAddress, int clientPort, SSLParameters sslParameters)
- throws IOException {
- super(address, port, clientAddress, clientPort);
- init(sslParameters);
- }
-
- /**
- * Constructor with 5 parameters: 1st is socket. Enhances an existing socket
- * with SSL functionality.
- *
- * @throws IOException if network fails
- */
- protected OpenSSLSocketImpl(Socket socket, String host, int port,
- boolean autoClose, SSLParameters sslParameters) throws IOException {
- super();
- this.socket = socket;
- this.timeout = socket.getSoTimeout();
- this.address = new InetSocketAddress(host, port);
- this.autoClose = autoClose;
- init(sslParameters);
- }
-
- /**
- * Initialize the SSL socket and set the certificates for the
- * future handshaking.
- */
- private void init(SSLParameters sslParameters) throws IOException {
- init(sslParameters,
- NativeCrypto.getSupportedProtocols(),
- NativeCrypto.getDefaultCipherSuites());
- }
-
- /**
- * Initialize the SSL socket and set the certificates for the
- * future handshaking.
- */
- private void init(SSLParameters sslParameters,
- String[] enabledProtocols,
- String[] enabledCipherSuites) throws IOException {
- this.sslParameters = sslParameters;
- this.enabledProtocols = enabledProtocols;
- this.enabledCipherSuites = enabledCipherSuites;
- updateInstanceCount(1);
- }
-
- /**
- * Gets the suitable session reference from the session cache container.
- *
- * @return OpenSSLSessionImpl
- */
- private OpenSSLSessionImpl getCachedClientSession(ClientSessionContext sessionContext) {
- if (super.getInetAddress() == null ||
- super.getInetAddress().getHostAddress() == null ||
- super.getInetAddress().getHostName() == null) {
- return null;
- }
- return (OpenSSLSessionImpl) sessionContext.getSession(
- super.getInetAddress().getHostName(),
- super.getPort());
- }
-
- /**
- * Ensures that logger is lazily loaded. The outer class seems to load
- * before logging is ready.
- */
- static class LoggerHolder {
- static final Logger logger = Logger.getLogger(OpenSSLSocketImpl.class.getName());
- }
-
- /**
- * Starts a TLS/SSL handshake on this connection using some native methods
- * from the OpenSSL library. It can negotiate new encryption keys, change
- * cipher suites, or initiate a new session. The certificate chain is
- * verified if the correspondent property in java.Security is set. All
- * listeners are notified at the end of the TLS/SSL handshake.
- *
- * @throws <code>IOException</code> if network fails
- */
- public void startHandshake() throws IOException {
- startHandshake(true);
- }
-
- /**
- * Perform the handshake
- * @param full If true, disable handshake cutthrough for a fully synchronous handshake
- */
- public synchronized void startHandshake(boolean full) throws IOException {
- synchronized (handshakeLock) {
- if (!handshakeStarted) {
- handshakeStarted = true;
- } else {
- return;
- }
- }
-
- this.sslNativePointer = NativeCrypto.SSL_new(sslParameters);
- // TODO move more code out of NativeCrypto.SSL_new
- NativeCrypto.setEnabledProtocols(sslNativePointer, enabledProtocols);
- NativeCrypto.setEnabledCipherSuites(sslNativePointer, enabledCipherSuites);
-
- boolean enableSessionCreation = sslParameters.getEnableSessionCreation();
- if (!enableSessionCreation) {
- NativeCrypto.SSL_set_session_creation_enabled(sslNativePointer,
- enableSessionCreation);
- }
-
- boolean client = sslParameters.getUseClientMode();
-
- AbstractSessionContext sessionContext;
- OpenSSLSessionImpl session;
- if (client) {
- // look for client session to reuse
- ClientSessionContext clientSessionContext = sslParameters.getClientSessionContext();
- sessionContext = clientSessionContext;
- session = getCachedClientSession(clientSessionContext);
- if (session != null) {
- NativeCrypto.SSL_set_session(sslNativePointer, session.sslSessionNativePointer);
- }
- } else {
- sessionContext = sslParameters.getServerSessionContext();
- session = null;
- }
-
- // setup peer certificate verification
- if (client) {
- // TODO support for anonymous cipher would require us to conditionally use SSL_VERIFY_NONE
- } else {
- // needing client auth takes priority...
- if (sslParameters.getNeedClientAuth()) {
- NativeCrypto.SSL_set_verify(sslNativePointer,
- NativeCrypto.SSL_VERIFY_PEER|
- NativeCrypto.SSL_VERIFY_FAIL_IF_NO_PEER_CERT|
- NativeCrypto.SSL_VERIFY_CLIENT_ONCE);
- // ... over just wanting it...
- } else if (sslParameters.getWantClientAuth()) {
- NativeCrypto.SSL_set_verify(sslNativePointer,
- NativeCrypto.SSL_VERIFY_PEER|
- NativeCrypto.SSL_VERIFY_CLIENT_ONCE);
- }
- // ... and it defaults properly so we don't need call SSL_set_verify in the common case.
- }
-
- if (client && full) {
- // we want to do a full synchronous handshake, so turn off cutthrough
- NativeCrypto.SSL_clear_mode(sslNativePointer, NativeCrypto.SSL_MODE_HANDSHAKE_CUTTHROUGH);
- }
-
- // BEGIN android-added
- // Temporarily use a different timeout for the handshake process
- int savedTimeout = timeout;
- if (handshakeTimeout >= 0) {
- setSoTimeout(handshakeTimeout);
- }
- // END android-added
-
-
- Socket socket = this.socket != null ? this.socket : this;
- int sslSessionNativePointer;
- try {
- sslSessionNativePointer = NativeCrypto.SSL_do_handshake(sslNativePointer, socket, this, this, timeout, client);
- } catch (CertificateException e) {
- throw new SSLPeerUnverifiedException(e.getMessage());
- }
- byte[] sessionId = OpenSSLSessionImpl.getId(sslSessionNativePointer);
- sslSession = (OpenSSLSessionImpl) sessionContext.getSession(sessionId);
- if (sslSession != null) {
- session.lastAccessedTime = System.currentTimeMillis();
- LoggerHolder.logger.fine("Reused cached session for "
- + getInetAddress() + ".");
- OpenSSLSessionImpl.freeImpl(sslSessionNativePointer);
- } else {
- if (!enableSessionCreation) {
- // Should have been prevented by NativeCrypto.SSL_set_session_creation_enabled
- throw new IllegalStateException("SSL Session may not be created");
- }
- byte[][] localCertificatesBytes = NativeCrypto.SSL_get_certificate(sslNativePointer);
- X509Certificate[] localCertificates;
- if (localCertificatesBytes == null) {
- localCertificates = null;
- } else {
- localCertificates = new X509Certificate[localCertificatesBytes.length];
- for (int i = 0; i < localCertificatesBytes.length; i++) {
- try {
- // TODO do not go through PEM decode, DER encode, DER decode
- localCertificates[i]
- = new X509CertImpl(
- javax.security.cert.X509Certificate.getInstance(
- localCertificatesBytes[i]).getEncoded());
- } catch (javax.security.cert.CertificateException e) {
- throw new IOException("Problem decoding local certificate", e);
- }
- }
- }
-
- if (address == null) {
- sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates,
- super.getInetAddress().getHostName(),
- super.getPort(), sessionContext);
- } else {
- sslSession = new OpenSSLSessionImpl(sslSessionNativePointer, localCertificates,
- address.getHostName(), address.getPort(),
- sessionContext);
- }
- // putSession will be done later in handshakeCompleted() callback
- if (handshakeCompleted) {
- sessionContext.putSession(sslSession);
- }
- LoggerHolder.logger.fine("Created new session for "
- + getInetAddress().getHostName() + ".");
- }
-
- // BEGIN android-added
- // Restore the original timeout now that the handshake is complete
- if (handshakeTimeout >= 0) {
- setSoTimeout(savedTimeout);
- }
- // END android-added
-
- // notifyHandshakeCompletedListeners will be done later in handshakeCompleted() callback
- if (handshakeCompleted) {
- notifyHandshakeCompletedListeners();
- }
-
- }
-
- /**
- * Implementation of NativeCrypto.HandshakeCompletedCallback
- * invoked via JNI from info_callback
- */
- public void handshakeCompleted() {
- handshakeCompleted = true;
-
- // If sslSession is null, the handshake was completed during
- // the call to NativeCrypto.SSL_do_handshake and not during a
- // later read operation. That means we do not need to fixup
- // the SSLSession and session cache or notify
- // HandshakeCompletedListeners, it will be done in
- // startHandshake.
- if (sslSession == null) {
- return;
- }
-
- // reset session id from the native pointer and update the
- // appropriate cache.
- sslSession.resetId();
- AbstractSessionContext sessionContext =
- (sslParameters.getUseClientMode())
- ? sslParameters.getClientSessionContext()
- : sslParameters.getServerSessionContext();
- sessionContext.putSession(sslSession);
-
- // let listeners know we are finally done
- notifyHandshakeCompletedListeners();
- }
-
- private void notifyHandshakeCompletedListeners() {
- if (listeners != null && !listeners.isEmpty()) {
- // notify the listeners
- HandshakeCompletedEvent event =
- new HandshakeCompletedEvent(this, sslSession);
- for (HandshakeCompletedListener listener : listeners) {
- try {
- listener.handshakeCompleted(event);
- } catch (RuntimeException e) {
- // TODO log?
- }
- }
- }
- }
-
- /**
- * Implementation of NativeCrypto.CertificateChainVerifier.
- *
- * @param bytes An array of certficates in PEM encode bytes
- * @param authMethod auth algorithm name
- *
- * @throws CertificateException if the certificate is untrusted
- */
- @SuppressWarnings("unused")
- public void verifyCertificateChain(byte[][] bytes, String authMethod) throws CertificateException {
- try {
- X509Certificate[] peerCertificateChain = new X509Certificate[bytes.length];
- for (int i = 0; i < bytes.length; i++) {
- peerCertificateChain[i] =
- new X509CertImpl(javax.security.cert.X509Certificate.getInstance(bytes[i]).getEncoded());
- }
-
- boolean client = sslParameters.getUseClientMode();
- if (client) {
- if (peerCertificateChain == null
- || peerCertificateChain.length == 0) {
- throw new SSLException("Server sends no certificate");
- }
- sslParameters.getTrustManager().checkServerTrusted(peerCertificateChain, authMethod);
- } else {
- sslParameters.getTrustManager().checkClientTrusted(peerCertificateChain, authMethod);
- }
-
- } catch (CertificateException e) {
- throw e;
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- /**
- * Returns an input stream for this SSL socket using native calls to the
- * OpenSSL library.
- *
- * @return: an input stream for reading bytes from this socket.
- * @throws: <code>IOException</code> if an I/O error occurs when creating
- * the input stream, the socket is closed, the socket is not
- * connected, or the socket input has been shutdown.
- */
- public InputStream getInputStream() throws IOException {
- synchronized(this) {
- if (is == null) {
- is = new SSLInputStream();
- }
-
- return is;
- }
- }
-
- /**
- * Returns an output stream for this SSL socket using native calls to the
- * OpenSSL library.
- *
- * @return an output stream for writing bytes to this socket.
- * @throws <code>IOException</code> if an I/O error occurs when creating
- * the output stream, or no connection to the socket exists.
- */
- public OutputStream getOutputStream() throws IOException {
- synchronized(this) {
- if (os == null) {
- os = new SSLOutputStream();
- }
-
- return os;
- }
- }
-
- /**
- * This method is not supported for this SSLSocket implementation
- * because reading from an SSLSocket may involve writing to the
- * network.
- */
- public void shutdownInput() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * This method is not supported for this SSLSocket implementation
- * because writing to an SSLSocket may involve reading from the
- * network.
- */
- public void shutdownOutput() throws IOException {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Reads with the native SSL_read function from the encrypted data stream
- * @return -1 if error or the end of the stream is reached.
- */
- private native int nativeread(int sslNativePointer, int timeout) throws IOException;
- private native int nativeread(int sslNativePointer, byte[] b, int off, int len, int timeout) throws IOException;
-
- /**
- * This inner class provides input data stream functionality
- * for the OpenSSL native implementation. It is used to
- * read data received via SSL protocol.
- */
- private class SSLInputStream extends InputStream {
- SSLInputStream() throws IOException {
- /**
- /* Note: When startHandshake() throws an exception, no
- * SSLInputStream object will be created.
- */
- OpenSSLSocketImpl.this.startHandshake(false);
- }
-
- /**
- * Reads one byte. If there is no data in the underlying buffer,
- * this operation can block until the data will be
- * available.
- * @return read value.
- * @throws <code>IOException</code>
- */
- public int read() throws IOException {
- synchronized(readLock) {
- return OpenSSLSocketImpl.this.nativeread(sslNativePointer, timeout);
- }
- }
-
- /**
- * Method acts as described in spec for superclass.
- * @see java.io.InputStream#read(byte[],int,int)
- */
- public int read(byte[] b, int off, int len) throws IOException {
- synchronized(readLock) {
- return OpenSSLSocketImpl.this.nativeread(sslNativePointer, b, off, len, timeout);
- }
- }
- }
-
- /**
- * Writes with the native SSL_write function to the encrypted data stream.
- */
- private native void nativewrite(int sslNativePointer, int b) throws IOException;
- private native void nativewrite(int sslNativePointer, byte[] b, int off, int len) throws IOException;
-
- /**
- * This inner class provides output data stream functionality
- * for the OpenSSL native implementation. It is used to
- * write data according to the encryption parameters given in SSL context.
- */
- private class SSLOutputStream extends OutputStream {
- SSLOutputStream() throws IOException {
- /**
- /* Note: When startHandshake() throws an exception, no
- * SSLOutputStream object will be created.
- */
- OpenSSLSocketImpl.this.startHandshake(false);
- }
-
- /**
- * Method acts as described in spec for superclass.
- * @see java.io.OutputStream#write(int)
- */
- public void write(int b) throws IOException {
- synchronized(writeLock) {
- OpenSSLSocketImpl.this.nativewrite(sslNativePointer, b);
- }
- }
-
- /**
- * Method acts as described in spec for superclass.
- * @see java.io.OutputStream#write(byte[],int,int)
- */
- public void write(byte[] b, int start, int len) throws IOException {
- synchronized(writeLock) {
- OpenSSLSocketImpl.this.nativewrite(sslNativePointer, b, start, len);
- }
- }
- }
-
-
- /**
- * The SSL session used by this connection is returned. The SSL session
- * determines which cipher suite should be used by all connections within
- * that session and which identities have the session's client and server.
- * This method starts the SSL handshake.
- * @return the SSLSession.
- * @throws <code>IOException</code> if the handshake fails
- */
- public SSLSession getSession() {
- try {
- startHandshake(true);
- } catch (IOException e) {
- // return an invalid session with
- // invalid cipher suite of "SSL_NULL_WITH_NULL_NULL"
- return SSLSessionImpl.NULL_SESSION;
- }
- return sslSession;
- }
-
- /**
- * Registers a listener to be notified that a SSL handshake
- * was successfully completed on this connection.
- * @throws <code>IllegalArgumentException</code> if listener is null.
- */
- public void addHandshakeCompletedListener(
- HandshakeCompletedListener listener) {
- if (listener == null) {
- throw new IllegalArgumentException("Provided listener is null");
- }
- if (listeners == null) {
- listeners = new ArrayList();
- }
- listeners.add(listener);
- }
-
- /**
- * The method removes a registered listener.
- * @throws IllegalArgumentException if listener is null or not registered
- */
- public void removeHandshakeCompletedListener(
- HandshakeCompletedListener listener) {
- if (listener == null) {
- throw new IllegalArgumentException("Provided listener is null");
- }
- if (listeners == null) {
- throw new IllegalArgumentException(
- "Provided listener is not registered");
- }
- if (!listeners.remove(listener)) {
- throw new IllegalArgumentException(
- "Provided listener is not registered");
- }
- }
-
- /**
- * Returns true if new SSL sessions may be established by this socket.
- *
- * @return true if the session may be created; false if a session already
- * exists and must be resumed.
- */
- public boolean getEnableSessionCreation() {
- return sslParameters.getEnableSessionCreation();
- }
-
- /**
- * Set a flag for the socket to inhibit or to allow the creation of a new
- * SSL sessions. If the flag is set to false, and there are no actual
- * sessions to resume, then there will be no successful handshaking.
- *
- * @param flag true if session may be created; false
- * if a session already exists and must be resumed.
- */
- public void setEnableSessionCreation(boolean flag) {
- sslParameters.setEnableSessionCreation(flag);
- }
-
- /**
- * The names of the cipher suites which could be used by the SSL connection
- * are returned.
- * @return an array of cipher suite names
- */
- public String[] getSupportedCipherSuites() {
- return NativeCrypto.getSupportedCipherSuites();
- }
-
- /**
- * The names of the cipher suites that are in use in the actual the SSL
- * connection are returned.
- *
- * @return an array of cipher suite names
- */
- public String[] getEnabledCipherSuites() {
- return enabledCipherSuites.clone();
- }
-
- /**
- * This method enables the cipher suites listed by
- * getSupportedCipherSuites().
- *
- * @param suites names of all the cipher suites to
- * put on use
- * @throws IllegalArgumentException when one or more of the
- * ciphers in array suites are not supported, or when the array
- * is null.
- */
- public void setEnabledCipherSuites(String[] suites) {
- enabledCipherSuites = NativeCrypto.checkEnabledCipherSuites(suites);
- }
-
- /**
- * The names of the protocols' versions that may be used on this SSL
- * connection.
- * @return an array of protocols names
- */
- public String[] getSupportedProtocols() {
- return NativeCrypto.getSupportedProtocols();
- }
-
- /**
- * The names of the protocols' versions that are in use on this SSL
- * connection.
- *
- * @return an array of protocols names
- */
- @Override
- public String[] getEnabledProtocols() {
- return enabledProtocols.clone();
- }
-
- /**
- * This method enables the protocols' versions listed by
- * getSupportedProtocols().
- *
- * @param protocols The names of all the protocols to put on use
- *
- * @throws IllegalArgumentException when one or more of the names in the
- * array are not supported, or when the array is null.
- */
- @Override
- public synchronized void setEnabledProtocols(String[] protocols) {
- enabledProtocols = NativeCrypto.checkEnabledProtocols(protocols);
- }
-
- /**
- * This method gives true back if the SSL socket is set to client mode.
- *
- * @return true if the socket should do the handshaking as client.
- */
- public boolean getUseClientMode() {
- return sslParameters.getUseClientMode();
- }
-
- /**
- * This method set the actual SSL socket to client mode.
- *
- * @param mode true if the socket starts in client
- * mode
- * @throws IllegalArgumentException if mode changes during
- * handshake.
- */
- public synchronized void setUseClientMode(boolean mode) {
- if (handshakeStarted) {
- throw new IllegalArgumentException(
- "Could not change the mode after the initial handshake has begun.");
- }
- sslParameters.setUseClientMode(mode);
- }
-
- /**
- * Returns true if the SSL socket requests client's authentication. Relevant
- * only for server sockets!
- *
- * @return true if client authentication is desired, false if not.
- */
- public boolean getWantClientAuth() {
- return sslParameters.getWantClientAuth();
- }
-
- /**
- * Returns true if the SSL socket needs client's authentication. Relevant
- * only for server sockets!
- *
- * @return true if client authentication is desired, false if not.
- */
- public boolean getNeedClientAuth() {
- return sslParameters.getNeedClientAuth();
- }
-
- /**
- * Sets the SSL socket to use client's authentication. Relevant only for
- * server sockets!
- *
- * @param need true if client authentication is
- * desired, false if not.
- */
- public void setNeedClientAuth(boolean need) {
- sslParameters.setNeedClientAuth(need);
- }
-
- /**
- * Sets the SSL socket to use client's authentication. Relevant only for
- * server sockets! Notice that in contrast to setNeedClientAuth(..) this
- * method will continue the negotiation if the client decide not to send
- * authentication credentials.
- *
- * @param want true if client authentication is
- * desired, false if not.
- */
- public void setWantClientAuth(boolean want) {
- sslParameters.setWantClientAuth(want);
- }
-
- /**
- * This method is not supported for SSLSocket implementation.
- */
- public void sendUrgentData(int data) throws IOException {
- throw new SocketException(
- "Method sendUrgentData() is not supported.");
- }
-
- /**
- * This method is not supported for SSLSocket implementation.
- */
- public void setOOBInline(boolean on) throws SocketException {
- throw new SocketException(
- "Methods sendUrgentData, setOOBInline are not supported.");
- }
-
- /**
- * Set the read timeout on this socket. The SO_TIMEOUT option, is specified
- * in milliseconds. The read operation will block indefinitely for a zero
- * value.
- *
- * @param timeout the read timeout value
- * @throws SocketException if an error occurs setting the option
- */
- public synchronized void setSoTimeout(int timeout) throws SocketException {
- super.setSoTimeout(timeout);
- this.timeout = timeout;
- }
-
- // BEGIN android-added
- /**
- * Set the handshake timeout on this socket. This timeout is specified in
- * milliseconds and will be used only during the handshake process.
- *
- * @param timeout the handshake timeout value
- */
- public synchronized void setHandshakeTimeout(int timeout) throws SocketException {
- this.handshakeTimeout = timeout;
- }
- // END android-added
-
- private native void nativeinterrupt(int sslNativePointer) throws IOException;
- private native void nativeclose(int sslNativePointer) throws IOException;
-
- /**
- * Closes the SSL socket. Once closed, a socket is not available for further
- * use anymore under any circumstance. A new socket must be created.
- *
- * @throws <code>IOException</code> if an I/O error happens during the
- * socket's closure.
- */
- public void close() throws IOException {
- // TODO: Close SSL sockets using a background thread so they close
- // gracefully.
-
- synchronized (handshakeLock) {
- if (!handshakeStarted) {
- // prevent further attemps to start handshake
- handshakeStarted = true;
-
- synchronized (this) {
- free();
-
- if (socket != null) {
- if (autoClose && !socket.isClosed()) socket.close();
- } else {
- if (!super.isClosed()) super.close();
- }
- }
-
- return;
- }
- }
-
- nativeinterrupt(sslNativePointer);
-
- synchronized (this) {
- synchronized (writeLock) {
- synchronized (readLock) {
-
- IOException pendingException = null;
-
- // Shut down the SSL connection, per se.
- try {
- if (handshakeStarted) {
- nativeclose(sslNativePointer);
- }
- } catch (IOException ex) {
- /*
- * Note the exception at this point, but try to continue
- * to clean the rest of this all up before rethrowing.
- */
- pendingException = ex;
- }
-
- /*
- * Even if the above call failed, it is still safe to free
- * the native structs, and we need to do so lest we leak
- * memory.
- */
- free();
-
- if (socket != null) {
- if (autoClose && !socket.isClosed())
- socket.close();
- } else {
- if (!super.isClosed())
- super.close();
- }
-
- if (pendingException != null) {
- throw pendingException;
- }
- }
- }
- }
- }
-
- private void free() {
- if (sslNativePointer == 0) {
- return;
- }
- NativeCrypto.SSL_free(sslNativePointer);
- sslNativePointer = 0;
- }
-
- protected void finalize() throws IOException {
- /*
- * Just worry about our own state. Notably we do not try and
- * close anything. The SocketImpl, either our own
- * PlainSocketImpl, or the Socket we are wrapping, will do
- * that. This might mean we do not properly SSL_shutdown, but
- * if you want to do that, properly close the socket yourself.
- *
- * The reason why we don't try to SSL_shutdown, is that there
- * can be a race between finalizers where the PlainSocketImpl
- * finalizer runs first and closes the socket. However, in the
- * meanwhile, the underlying file descriptor could be reused
- * for another purpose. If we call SSL_shutdown, the
- * underlying socket BIOs still have the old file descriptor
- * and will write the close notify to some unsuspecting
- * reader.
- */
- updateInstanceCount(-1);
- free();
- }
-
- /**
- * Verifies an RSA signature. Conceptually, this method doesn't really
- * belong here, but due to its native code being closely tied to OpenSSL
- * (just like the rest of this class), we put it here for the time being.
- * This also solves potential problems with native library initialization.
- *
- * @param message The message to verify
- * @param signature The signature to verify
- * @param algorithm The hash/sign algorithm to use, i.e. "RSA-SHA1"
- * @param key The RSA public key to use
- * @return true if the verification succeeds, false otherwise
- */
- public static boolean verifySignature(byte[] message, byte[] signature, String algorithm, RSAPublicKey key) {
- byte[] modulus = key.getModulus().toByteArray();
- byte[] exponent = key.getPublicExponent().toByteArray();
-
- return nativeverifysignature(message, signature, algorithm, modulus, exponent) == 1;
- }
-
- private static native int nativeverifysignature(byte[] message, byte[] signature,
- String algorithm, byte[] modulus, byte[] exponent);
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImplWrapper.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImplWrapper.java
deleted file mode 100644
index 959f2a0..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImplWrapper.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketException;
-
-/**
- * This class wraps the SSL functionality over an existing conneted socket.
- */
-public class OpenSSLSocketImplWrapper extends OpenSSLSocketImpl {
-
- private Socket socket;
-
- protected OpenSSLSocketImplWrapper(Socket socket, String host, int port,
- boolean autoClose, SSLParameters sslParameters) throws IOException {
- super(socket, host, port, autoClose, sslParameters);
- if (!socket.isConnected()) {
- throw new SocketException("Socket is not connected.");
- }
- this.socket = socket;
- }
-
- @Override
- public void connect(SocketAddress sockaddr, int timeout)
- throws IOException {
- throw new IOException("Underlying socket is already connected.");
- }
-
- @Override
- public void connect(SocketAddress sockaddr) throws IOException {
- throw new IOException("Underlying socket is already connected.");
- }
-
- @Override
- public void bind(SocketAddress sockaddr) throws IOException {
- throw new IOException("Underlying socket is already connected.");
- }
-
- @Override
- public SocketAddress getRemoteSocketAddress() {
- return socket.getRemoteSocketAddress();
- }
-
- @Override
- public SocketAddress getLocalSocketAddress() {
- return socket.getLocalSocketAddress();
- }
-
- @Override
- public InetAddress getLocalAddress() {
- return socket.getLocalAddress();
- }
-
- @Override
- public InetAddress getInetAddress() {
- return socket.getInetAddress();
- }
-
- @Override
- public String toString() {
- return "SSL socket over " + socket.toString();
- }
-
- @Override
- public void setSoLinger(boolean on, int linger) throws SocketException {
- socket.setSoLinger(on, linger);
- }
-
- @Override
- public void setTcpNoDelay(boolean on) throws SocketException {
- socket.setTcpNoDelay(on);
- }
-
- @Override
- public void setReuseAddress(boolean on) throws SocketException {
- socket.setReuseAddress(on);
- }
-
- @Override
- public void setKeepAlive(boolean on) throws SocketException {
- socket.setKeepAlive(on);
- }
-
- @Override
- public void setTrafficClass(int tos) throws SocketException {
- socket.setTrafficClass(tos);
- }
-
- @Override
- public void setSoTimeout(int to) throws SocketException {
- socket.setSoTimeout(to);
- super.setSoTimeout(to);
- }
-
- @Override
- public void setSendBufferSize(int size) throws SocketException {
- socket.setSendBufferSize(size);
- }
-
- @Override
- public void setReceiveBufferSize(int size) throws SocketException {
- socket.setReceiveBufferSize(size);
- }
-
- @Override
- public boolean getTcpNoDelay() throws SocketException {
- return socket.getTcpNoDelay();
- }
-
- @Override
- public boolean getReuseAddress() throws SocketException {
- return socket.getReuseAddress();
- }
-
- @Override
- public boolean getOOBInline() throws SocketException {
- return socket.getOOBInline();
- }
-
- @Override
- public boolean getKeepAlive() throws SocketException {
- return socket.getKeepAlive();
- }
-
- @Override
- public int getTrafficClass() throws SocketException {
- return socket.getTrafficClass();
- }
-
- @Override
- public int getSoTimeout() throws SocketException {
- return socket.getSoTimeout();
- }
-
- @Override
- public int getSoLinger() throws SocketException {
- return socket.getSoLinger();
- }
-
- @Override
- public int getSendBufferSize() throws SocketException {
- return socket.getSendBufferSize();
- }
-
- @Override
- public int getReceiveBufferSize() throws SocketException {
- return socket.getReceiveBufferSize();
- }
-
- @Override
- public boolean isConnected() {
- return socket.isConnected();
- }
-
- @Override
- public boolean isClosed() {
- return socket.isClosed();
- }
-
- @Override
- public boolean isBound() {
- return socket.isBound();
- }
-
- @Override
- public boolean isOutputShutdown() {
- return socket.isOutputShutdown();
- }
-
- @Override
- public boolean isInputShutdown() {
- return socket.isInputShutdown();
- }
-
- @Override
- public int getPort() {
- return socket.getPort();
- }
-
- @Override
- public int getLocalPort() {
- return socket.getLocalPort();
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/PRF.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/PRF.java
deleted file mode 100644
index c2f91a3..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/PRF.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.Logger;
-
-import java.security.GeneralSecurityException;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.Arrays;
-import javax.net.ssl.SSLException;
-import javax.crypto.Mac;
-import javax.crypto.spec.SecretKeySpec;
-
-/**
- * This class provides functionality for computation
- * of PRF values for TLS (http://www.ietf.org/rfc/rfc2246.txt)
- * and SSL v3 (http://wp.netscape.com/eng/ssl3) protocols.
- */
-public class PRF {
- private static Logger.Stream logger = Logger.getStream("prf");
-
- private static Mac md5_mac;
- private static Mac sha_mac;
- protected static MessageDigest md5;
- protected static MessageDigest sha;
- private static int md5_mac_length;
- private static int sha_mac_length;
-
- static private void init() {
- try {
- md5_mac = Mac.getInstance("HmacMD5");
- sha_mac = Mac.getInstance("HmacSHA1");
- } catch (NoSuchAlgorithmException e) {
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLException(
- "There is no provider of HmacSHA1 or HmacMD5 "
- + "algorithms installed in the system"));
- }
- md5_mac_length = md5_mac.getMacLength();
- sha_mac_length = sha_mac.getMacLength();
- try {
- md5 = MessageDigest.getInstance("MD5");
- sha = MessageDigest.getInstance("SHA-1");
- } catch (Exception e) {
- throw new AlertException(AlertProtocol.INTERNAL_ERROR,
- new SSLException(
- "Could not initialize the Digest Algorithms."));
- }
- }
-
- /**
- * Computes the value of SSLv3 pseudo random function.
- * @param out: the buffer to fill up with the value of the function.
- * @param secret: the buffer containing the secret value to generate prf.
- * @param seed: the seed to be used.
- */
- static synchronized void computePRF_SSLv3(byte[] out, byte[] secret, byte[] seed) {
- if (sha == null) {
- init();
- }
- int pos = 0;
- int iteration = 1;
- byte[] digest;
- while (pos < out.length) {
- byte[] pref = new byte[iteration];
- Arrays.fill(pref, (byte) (64 + iteration++));
- sha.update(pref);
- sha.update(secret);
- sha.update(seed);
- md5.update(secret);
- md5.update(sha.digest());
- digest = md5.digest(); // length == 16
- if (pos + 16 > out.length) {
- System.arraycopy(digest, 0, out, pos, out.length - pos);
- pos = out.length;
- } else {
- System.arraycopy(digest, 0, out, pos, 16);
- pos += 16;
- }
- }
- }
-
- /**
- * Computes the value of TLS pseudo random function.
- * @param out: the buffer to fill up with the value of the function.
- * @param secret: the buffer containing the secret value to generate prf.
- * @param str_bytes: the label bytes to be used.
- * @param seed: the seed to be used.
- */
- synchronized static void computePRF(byte[] out, byte[] secret,
- byte[] str_byts, byte[] seed) throws GeneralSecurityException {
- if (sha_mac == null) {
- init();
- }
- // Do concatenation of the label with the seed:
- // (metterings show that is is faster to concatenate the arrays
- // and to call HMAC.update on cancatenation, than twice call for
- // each of the part, i.e.:
- // time(HMAC.update(label+seed))
- // < time(HMAC.update(label)) + time(HMAC.update(seed))
- // but it takes more memmory (approximaty on 4%)
- /*
- byte[] tmp_seed = new byte[seed.length + str_byts.length];
- System.arraycopy(str_byts, 0, tmp_seed, 0, str_byts.length);
- System.arraycopy(seed, 0, tmp_seed, str_byts.length, seed.length);
- seed = tmp_seed;
- */
- SecretKeySpec keyMd5;
- SecretKeySpec keySha1;
- if ((secret == null) || (secret.length == 0)) {
- secret = new byte[8];
- keyMd5 = new SecretKeySpec(secret, "HmacMD5");
- keySha1 = new SecretKeySpec(secret, "HmacSHA1");
- } else {
- int length = secret.length >> 1; // division by 2
- int offset = secret.length & 1; // remainder
- keyMd5 = new SecretKeySpec(secret, 0, length + offset,
- "HmacMD5");
- keySha1 = new SecretKeySpec(secret, length, length
- + offset, "HmacSHA1");
- }
-
- //byte[] str_byts = label.getBytes();
-
- if (logger != null) {
- logger.println("secret["+secret.length+"]: ");
- logger.printAsHex(16, "", " ", secret);
- logger.println("label["+str_byts.length+"]: ");
- logger.printAsHex(16, "", " ", str_byts);
- logger.println("seed["+seed.length+"]: ");
- logger.printAsHex(16, "", " ", seed);
- logger.println("MD5 key:");
- logger.printAsHex(16, "", " ", keyMd5.getEncoded());
- logger.println("SHA1 key:");
- logger.printAsHex(16, "", " ", keySha1.getEncoded());
- }
-
- md5_mac.init(keyMd5);
- sha_mac.init(keySha1);
-
- int pos = 0;
- md5_mac.update(str_byts);
- byte[] hash = md5_mac.doFinal(seed); // A(1)
- while (pos < out.length) {
- md5_mac.update(hash);
- md5_mac.update(str_byts);
- md5_mac.update(seed);
- if (pos + md5_mac_length < out.length) {
- md5_mac.doFinal(out, pos);
- pos += md5_mac_length;
- } else {
- System.arraycopy(md5_mac.doFinal(), 0, out,
- pos, out.length - pos);
- break;
- }
- // make A(i)
- hash = md5_mac.doFinal(hash);
- }
- if (logger != null) {
- logger.println("P_MD5:");
- logger.printAsHex(md5_mac_length, "", " ", out);
- }
-
- pos = 0;
- sha_mac.update(str_byts);
- hash = sha_mac.doFinal(seed); // A(1)
- byte[] sha1hash;
- while (pos < out.length) {
- sha_mac.update(hash);
- sha_mac.update(str_byts);
- sha1hash = sha_mac.doFinal(seed);
- for (int i = 0; (i < sha_mac_length) & (pos < out.length); i++) {
- out[pos++] ^= sha1hash[i];
- }
- // make A(i)
- hash = sha_mac.doFinal(hash);
- }
-
- if (logger != null) {
- logger.println("PRF:");
- logger.printAsHex(sha_mac_length, "", " ", out);
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java
deleted file mode 100644
index def27f9..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ProtocolVersion.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.util.Hashtable;
-
-/**
- *
- * Represents Protocol Version
- */
-public class ProtocolVersion {
- /**
- * Protocols supported by this provider implementation
- */
- public static final String[] supportedProtocols = new String[] { "TLSv1",
- "SSLv3" };
-
- private static Hashtable<String, ProtocolVersion> protocolsByName = new Hashtable<String, ProtocolVersion>(4);
-
- /**
- *
- * Returns true if protocol version is supported
- *
- * @param version
- */
- public static boolean isSupported(byte[] version) {
- if (version[0] != 3 || (version[1] != 0 && version[1] != 1)) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns ProtocolVersion
- *
- * @param version
- * @return
- */
- public static ProtocolVersion getByVersion(byte[] version) {
- if (version[0] == 3) {
- if (version[1] == 1) {
- return TLSv1;
- }
- if (version[1] == 0) {
- return SSLv3;
- }
- }
- return null;
- }
-
- /**
- * Returns true if provider supports protocol version
- *
- * @param name
- * @return
- */
- public static boolean isSupported(String name) {
- return protocolsByName.containsKey(name);
- }
-
- /**
- * Returns ProtocolVersion
- *
- * @param name
- * @return
- */
- public static ProtocolVersion getByName(String name) {
- return protocolsByName.get(name);
- }
-
- /**
- * Highest protocol version supported by provider implementation
- *
- * @param protocols
- * @return
- */
- public static ProtocolVersion getLatestVersion(String[] protocols) {
- if (protocols == null || protocols.length == 0) {
- return null;
- }
- ProtocolVersion latest = getByName(protocols[0]);
- ProtocolVersion current;
- for (int i = 1; i < protocols.length; i++) {
- current = getByName(protocols[i]);
- if (current == null) {
- continue;
- }
- if ((latest == null)
- || (latest.version[0] < current.version[0])
- || (latest.version[0] == current.version[0] && latest.version[1] < current.version[1])) {
- latest = current;
- }
- }
- return latest;
-
- }
-
- /**
- * SSL 3.0 protocol version
- */
- public static ProtocolVersion SSLv3 = new ProtocolVersion("SSLv3",
- new byte[] { 3, 0 });
-
- /**
- * TLS 1.0 protocol version
- */
- public static ProtocolVersion TLSv1 = new ProtocolVersion("TLSv1",
- new byte[] { 3, 1 });
-
- static {
- protocolsByName.put(SSLv3.name, SSLv3);
- protocolsByName.put(TLSv1.name, TLSv1);
- protocolsByName.put("SSL", SSLv3);
- protocolsByName.put("TLS", TLSv1);
- }
-
- /**
- * Protocol name
- */
- public final String name;
-
- /**
- * Protocol version as byte array
- */
- public final byte[] version;
-
- private ProtocolVersion(String name, byte[] version) {
- this.name = name;
- this.version = version;
- }
-
- /**
- * Compares this ProtocolVersion to the specified object.
- */
- @Override
- public boolean equals(Object o) {
- if (o instanceof ProtocolVersion
- && this.version[0] == ((ProtocolVersion) o).version[0]
- && this.version[1] == ((ProtocolVersion) o).version[1]) {
- return true;
- }
- return false;
- }
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLBufferedInput.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLBufferedInput.java
deleted file mode 100644
index 31bb681..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLBufferedInput.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.SSLInputStream;
-
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
-/**
- * This is a wrapper input stream for ByteBuffer data source.
- * Among with the read functionality it provides info
- * about number of cunsumed bytes from the source ByteBuffer.
- * The source ByteBuffer object can be reseted.
- * So one instance of this wrapper can be reused for several
- * ByteBuffer data sources.
- */
-public class SSLBufferedInput extends SSLInputStream {
-
- private ByteBuffer in;
- private int bytik;
- private int consumed = 0;
-
- /**
- * Constructor
- */
- protected SSLBufferedInput() {}
-
- /**
- * Sets the buffer as a data source
- */
- protected void setSourceBuffer(ByteBuffer in) {
- consumed = 0;
- this.in = in;
- }
-
- @Override
- public int available() throws IOException {
- // in assumption that the buffer has been set
- return in.remaining();
- }
-
- /**
- * Returns the number of consumed bytes.
- */
- protected int consumed() {
- return consumed;
- }
-
- /**
- * Reads the following byte value. If there are no bytes in the source
- * buffer, method throws java.nio.BufferUnderflowException.
- */
- @Override
- public int read() throws IOException {
- // TODO: implement optimized read(int)
- // and read(byte[], int, int) methods
- bytik = in.get() & 0x00FF;
- consumed ++;
- return bytik;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLClientSessionCache.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLClientSessionCache.java
deleted file mode 100644
index 8a73fa5..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLClientSessionCache.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLSession;
-
-/**
- * A persistent {@link javax.net.ssl.SSLSession} cache used by
- * {@link javax.net.ssl.SSLSessionContext} to share client-side SSL sessions
- * across processes. For example, this cache enables applications to
- * persist and reuse sessions across restarts.
- *
- * <p>The {@code SSLSessionContext} implementation converts
- * {@code SSLSession}s into raw bytes and vice versa. The exact makeup of the
- * session data is dependent upon the caller's implementation and is opaque to
- * the {@code SSLClientSessionCache} implementation.
- */
-public interface SSLClientSessionCache {
-
- /**
- * Gets data from a pre-existing session for a given server host and port.
- *
- * @param host from {@link javax.net.ssl.SSLSession#getPeerHost()}
- * @param port from {@link javax.net.ssl.SSLSession#getPeerPort()}
- * @return the session data or null if none is cached
- * @throws NullPointerException if host is null
- */
- public byte[] getSessionData(String host, int port);
-
- /**
- * Stores session data for the given session.
- *
- * @param session to cache data for
- * @param sessionData to cache
- * @throws NullPointerException if session, result of
- * {@code session.getPeerHost()} or data is null
- */
- public void putSessionData(SSLSession session, byte[] sessionData);
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java
deleted file mode 100644
index 34942e1..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLContextImpl.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.SSLEngineImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLParameters;
-// BEGIN android-removed
-// import org.apache.harmony.xnet.provider.jsse.SSLServerSocketFactoryImpl;
-// END android-removed
-
-import java.security.KeyManagementException;
-import java.security.SecureRandom;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.SSLContextSpi;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLServerSocketFactory;
-import javax.net.ssl.SSLSessionContext;
-import javax.net.ssl.SSLSocketFactory;
-import javax.net.ssl.TrustManager;
-
-// BEGIN android-note
-// Modified heavily during SSLSessionContext refactoring. Added support for
-// persistent session caches.
-// END android-note
-
-/**
- * Implementation of SSLContext service provider interface.
- */
-public class SSLContextImpl extends SSLContextSpi {
-
- /** Client session cache. */
- private ClientSessionContext clientSessionContext;
-
- /** Server session cache. */
- private ServerSessionContext serverSessionContext;
-
- protected SSLParameters sslParameters;
-
- public SSLContextImpl() {
- super();
- }
-
- @Override
- public void engineInit(KeyManager[] kms, TrustManager[] tms,
- SecureRandom sr) throws KeyManagementException {
- engineInit(kms, tms, sr, null, null);
- }
-
- /**
- * Initializes this {@code SSLContext} instance. All of the arguments are
- * optional, and the security providers will be searched for the required
- * implementations of the needed algorithms.
- *
- * @param kms the key sources or {@code null}
- * @param tms the trust decision sources or {@code null}
- * @param sr the randomness source or {@code null}
- * @param clientCache persistent client session cache or {@code null}
- * @param serverCache persistent server session cache or {@code null}
- * @throws KeyManagementException if initializing this instance fails
- */
- public void engineInit(KeyManager[] kms, TrustManager[] tms,
- SecureRandom sr, SSLClientSessionCache clientCache,
- SSLServerSessionCache serverCache) throws KeyManagementException {
- sslParameters = new SSLParameters(kms, tms, sr,
- clientCache, serverCache);
- clientSessionContext = sslParameters.getClientSessionContext();
- serverSessionContext = sslParameters.getServerSessionContext();
- }
-
- public SSLSocketFactory engineGetSocketFactory() {
- if (sslParameters == null) {
- throw new IllegalStateException("SSLContext is not initiallized.");
- }
- return new OpenSSLSocketFactoryImpl(sslParameters);
- }
-
- @Override
- public SSLServerSocketFactory engineGetServerSocketFactory() {
- if (sslParameters == null) {
- throw new IllegalStateException("SSLContext is not initiallized.");
- }
- return new OpenSSLServerSocketFactoryImpl(sslParameters);
- }
-
- @Override
- public SSLEngine engineCreateSSLEngine(String host, int port) {
- if (sslParameters == null) {
- throw new IllegalStateException("SSLContext is not initiallized.");
- }
- return new SSLEngineImpl(host, port,
- (SSLParameters) sslParameters.clone());
- }
-
- @Override
- public SSLEngine engineCreateSSLEngine() {
- if (sslParameters == null) {
- throw new IllegalStateException("SSLContext is not initiallized.");
- }
- return new SSLEngineImpl((SSLParameters) sslParameters.clone());
- }
-
- @Override
- public ServerSessionContext engineGetServerSessionContext() {
- return serverSessionContext;
- }
-
- @Override
- public ClientSessionContext engineGetClientSessionContext() {
- return clientSessionContext;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineAppData.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineAppData.java
deleted file mode 100644
index 9a2cb5e..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineAppData.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-
-import java.nio.ByteBuffer;
-import javax.net.ssl.SSLException;
-
-/**
- * This class is used to retrieve the application data
- * arrived for the SSLEngine.
- */
-public class SSLEngineAppData implements org.apache.harmony.xnet.provider.jsse.Appendable {
-
- /**
- * Buffer containing received application data.
- */
- byte[] buffer;
-
- /**
- * Constructor
- */
- protected SSLEngineAppData() {}
-
- /**
- * Stores received data. The source data is not cloned,
- * just the array reference is remembered into the buffer field.
- */
- public void append(byte[] src) {
- if (buffer != null) {
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLException("Attempt to override the data"));
- }
- buffer = src;
- }
-
- /**
- * Places the data from the buffer into the array of destination
- * ByteBuffer objects.
- */
- protected int placeTo(ByteBuffer[] dsts, int offset, int length) {
- if (buffer == null) {
- return 0;
- }
- int pos = 0;
- int len = buffer.length;
- int rem;
- // write data to the buffers
- for (int i=offset; i<offset+length; i++) {
- rem = dsts[i].remaining();
- // TODO: optimization work - use hasArray, array(), arraycopy
- if (len - pos < rem) {
- // can fully write remaining data into buffer
- dsts[i].put(buffer, pos, len - pos);
- pos = len;
- // data was written, exit
- break;
- }
- // write chunk of data
- dsts[i].put(buffer, pos, rem);
- pos += rem;
- }
- if (pos != len) {
- // The data did not feet into the buffers,
- // it should not happen, because the destination buffers
- // had been checked for the space before record unwrapping.
- // But if it so, we should allert about internal error.
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLException(
- "The received application data could not be fully written"
- + "into the destination buffers"));
- }
- buffer = null;
- return len;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineDataStream.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineDataStream.java
deleted file mode 100644
index e209dd1..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineDataStream.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.nio.ByteBuffer;
-
-/**
- * This class provides the DataStream functionality
- * implemented over the array of ByteBuffer instances.
- * Among with the data chunks read functionality
- * it provides the info about amount of consumed data.
- * The source ByteBuffer objects can be replaced by other.
- * So one instance of this wrapper can be reused for several
- * data sources.
- */
-public class SSLEngineDataStream implements DataStream {
-
- private ByteBuffer[] srcs;
- private int offset;
- private int limit;
-
- private int available;
- private int consumed;
-
- protected SSLEngineDataStream() {}
-
- protected void setSourceBuffers(ByteBuffer[] srcs, int offset, int length) {
- this.srcs = srcs;
- this.offset = offset;
- this.limit = offset+length;
- this.consumed = 0;
- this.available = 0;
- for (int i=offset; i<limit; i++) {
- if (srcs[i] == null) {
- throw new IllegalStateException(
- "Some of the input parameters are null");
- }
- available += srcs[i].remaining();
- }
- }
-
- public int available() {
- return available;
- }
-
- public boolean hasData() {
- return available > 0;
- }
-
- public byte[] getData(int length) {
- // TODO: optimization work:
- // use ByteBuffer.get(byte[],int,int)
- // and ByteBuffer.hasArray() methods
- int len = (length < available) ? length : available;
- available -= len;
- consumed += len;
- byte[] res = new byte[len];
- int pos = 0;
- loop:
- for (; offset<limit; offset++) {
- while (srcs[offset].hasRemaining()) {
- res[pos++] = srcs[offset].get();
- len --;
- if (len == 0) {
- break loop;
- }
- }
- }
- return res;
- }
-
- protected int consumed() {
- return consumed;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineImpl.java
deleted file mode 100644
index c28a311..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLEngineImpl.java
+++ /dev/null
@@ -1,769 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.SSLSessionImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLEngineDataStream;
-
-import java.io.IOException;
-import java.nio.BufferUnderflowException;
-import java.nio.ByteBuffer;
-import java.nio.ReadOnlyBufferException;
-import javax.net.ssl.SSLEngine;
-import javax.net.ssl.SSLHandshakeException;
-import javax.net.ssl.SSLEngineResult;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.SSLSession;
-
-/**
- * Implementation of SSLEngine.
- * @see javax.net.ssl.SSLEngine class documentation for more information.
- */
-public class SSLEngineImpl extends SSLEngine {
-
- // indicates if peer mode was set
- private boolean peer_mode_was_set = false;
- // indicates if handshake has been started
- private boolean handshake_started = false;
- // indicates if inbound operations finished
- private boolean isInboundDone = false;
- // indicates if outbound operations finished
- private boolean isOutboundDone = false;
- // indicates if close_notify alert had been sent to another peer
- private boolean close_notify_was_sent = false;
- // indicates if close_notify alert had been received from another peer
- private boolean close_notify_was_received = false;
- // indicates if engine was closed (it means that
- // all the works on it are done, except (probably) some finalizing work)
- private boolean engine_was_closed = false;
- // indicates if engine was shutted down (it means that
- // all cleaning work had been done and the engine is not operable)
- private boolean engine_was_shutteddown = false;
-
- // record protocol to be used
- protected SSLRecordProtocol recordProtocol;
- // input stream for record protocol
- private SSLBufferedInput recProtIS;
- // handshake protocol to be used
- private HandshakeProtocol handshakeProtocol;
- // alert protocol to be used
- private AlertProtocol alertProtocol;
- // place where application data will be stored
- private SSLEngineAppData appData;
- // outcoming application data stream
- private SSLEngineDataStream dataStream = new SSLEngineDataStream();
- // active session object
- private SSLSessionImpl session;
-
- // peer configuration parameters
- protected SSLParameters sslParameters;
-
- // in case of emergency situations when data could not be
- // placed in destination buffers it will be stored in this
- // fields
- private byte[] remaining_wrapped_data = null;
- private byte[] remaining_hsh_data = null;
-
- // logger
- private Logger.Stream logger = Logger.getStream("engine");
-
- /**
- * Ctor
- * @param sslParameters: SSLParameters
- */
- protected SSLEngineImpl(SSLParameters sslParameters) {
- super();
- this.sslParameters = sslParameters;
- }
-
- /**
- * Ctor
- * @param host: String
- * @param port: int
- * @param sslParameters: SSLParameters
- */
- protected SSLEngineImpl(String host, int port, SSLParameters sslParameters) {
- super(host, port);
- this.sslParameters = sslParameters;
- }
-
- /**
- * Starts the handshake.
- * @throws SSLException
- * @see javax.net.ssl.SSLEngine#beginHandshake() method documentation
- * for more information
- */
- @Override
- public void beginHandshake() throws SSLException {
- if (engine_was_closed) {
- throw new SSLException("Engine has already been closed.");
- }
- if (!peer_mode_was_set) {
- throw new IllegalStateException("Client/Server mode was not set");
- }
- if (!handshake_started) {
- handshake_started = true;
- if (getUseClientMode()) {
- handshakeProtocol = new ClientHandshakeImpl(this);
- } else {
- handshakeProtocol = new ServerHandshakeImpl(this);
- }
- appData = new SSLEngineAppData();
- alertProtocol = new AlertProtocol();
- recProtIS = new SSLBufferedInput();
- recordProtocol = new SSLRecordProtocol(handshakeProtocol,
- alertProtocol, recProtIS, appData);
- }
- handshakeProtocol.start();
- }
-
- /**
- * Closes inbound operations of this engine
- * @throws SSLException
- * @see javax.net.ssl.SSLEngine#closeInbound() method documentation
- * for more information
- */
- @Override
- public void closeInbound() throws SSLException {
- if (logger != null) {
- logger.println("closeInbound() "+isInboundDone);
- }
- if (isInboundDone) {
- return;
- }
- isInboundDone = true;
- engine_was_closed = true;
- if (handshake_started) {
- if (!close_notify_was_received) {
- if (session != null) {
- session.invalidate();
- }
- alertProtocol.alert(AlertProtocol.FATAL,
- AlertProtocol.INTERNAL_ERROR);
- throw new SSLException("Inbound is closed before close_notify "
- + "alert has been received.");
- }
- } else {
- // engine is closing before initial handshake has been made
- shutdown();
- }
- }
-
- /**
- * Closes outbound operations of this engine
- * @see javax.net.ssl.SSLEngine#closeOutbound() method documentation
- * for more information
- */
- @Override
- public void closeOutbound() {
- if (logger != null) {
- logger.println("closeOutbound() "+isOutboundDone);
- }
- if (isOutboundDone) {
- return;
- }
- isOutboundDone = true;
- if (handshake_started) {
- // initial handshake had been started
- alertProtocol.alert(AlertProtocol.WARNING,
- AlertProtocol.CLOSE_NOTIFY);
- close_notify_was_sent = true;
- } else {
- // engine is closing before initial handshake has been made
- shutdown();
- }
- engine_was_closed = true;
- }
-
- /**
- * Returns handshake's delegated tasks to be run
- * @return the delegated task to be executed.
- * @see javax.net.ssl.SSLEngine#getDelegatedTask() method documentation
- * for more information
- */
- @Override
- public Runnable getDelegatedTask() {
- return handshakeProtocol.getTask();
- }
-
- /**
- * Returns names of supported cipher suites.
- * @return array of strings containing the names of supported cipher suites
- * @see javax.net.ssl.SSLEngine#getSupportedCipherSuites() method
- * documentation for more information
- */
- @Override
- public String[] getSupportedCipherSuites() {
- return CipherSuite.getSupportedCipherSuiteNames();
- }
-
- // --------------- SSLParameters based methods ---------------------
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getEnabledCipherSuites() method
- * documentation for more information
- */
- @Override
- public String[] getEnabledCipherSuites() {
- return sslParameters.getEnabledCipherSuites();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setEnabledCipherSuites(String[]) method
- * documentation for more information
- */
- @Override
- public void setEnabledCipherSuites(String[] suites) {
- sslParameters.setEnabledCipherSuites(suites);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getSupportedProtocols() method
- * documentation for more information
- */
- @Override
- public String[] getSupportedProtocols() {
- return ProtocolVersion.supportedProtocols.clone();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getEnabledProtocols() method
- * documentation for more information
- */
- @Override
- public String[] getEnabledProtocols() {
- return sslParameters.getEnabledProtocols();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setEnabledProtocols(String[]) method
- * documentation for more information
- */
- @Override
- public void setEnabledProtocols(String[] protocols) {
- sslParameters.setEnabledProtocols(protocols);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setUseClientMode(boolean) method
- * documentation for more information
- */
- @Override
- public void setUseClientMode(boolean mode) {
- if (handshake_started) {
- throw new IllegalArgumentException(
- "Could not change the mode after the initial handshake has begun.");
- }
- sslParameters.setUseClientMode(mode);
- peer_mode_was_set = true;
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getUseClientMode() method
- * documentation for more information
- */
- @Override
- public boolean getUseClientMode() {
- return sslParameters.getUseClientMode();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setNeedClientAuth(boolean) method
- * documentation for more information
- */
- @Override
- public void setNeedClientAuth(boolean need) {
- sslParameters.setNeedClientAuth(need);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getNeedClientAuth() method
- * documentation for more information
- */
- @Override
- public boolean getNeedClientAuth() {
- return sslParameters.getNeedClientAuth();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setWantClientAuth(boolean) method
- * documentation for more information
- */
- @Override
- public void setWantClientAuth(boolean want) {
- sslParameters.setWantClientAuth(want);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getWantClientAuth() method
- * documentation for more information
- */
- @Override
- public boolean getWantClientAuth() {
- return sslParameters.getWantClientAuth();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#setEnableSessionCreation(boolean) method
- * documentation for more information
- */
- @Override
- public void setEnableSessionCreation(boolean flag) {
- sslParameters.setEnableSessionCreation(flag);
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getEnableSessionCreation() method
- * documentation for more information
- */
- @Override
- public boolean getEnableSessionCreation() {
- return sslParameters.getEnableSessionCreation();
- }
-
- // -----------------------------------------------------------------
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getHandshakeStatus() method
- * documentation for more information
- */
- @Override
- public SSLEngineResult.HandshakeStatus getHandshakeStatus() {
- if (!handshake_started || engine_was_shutteddown) {
- // initial handshake has not been started yet
- return SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING;
- }
- if (alertProtocol.hasAlert()) {
- // need to send an alert
- return SSLEngineResult.HandshakeStatus.NEED_WRAP;
- }
- if (close_notify_was_sent && !close_notify_was_received) {
- // waiting for "close_notify" response
- return SSLEngineResult.HandshakeStatus.NEED_UNWRAP;
- }
- return handshakeProtocol.getStatus();
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#getSession() method
- * documentation for more information
- */
- @Override
- public SSLSession getSession() {
- if (session != null) {
- return session;
- }
- return SSLSessionImpl.NULL_SESSION;
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#isInboundDone() method
- * documentation for more information
- */
- @Override
- public boolean isInboundDone() {
- return isInboundDone || engine_was_closed;
- }
-
- /**
- * This method works according to the specification of implemented class.
- * @see javax.net.ssl.SSLEngine#isOutboundDone() method
- * documentation for more information
- */
- @Override
- public boolean isOutboundDone() {
- return isOutboundDone;
- }
-
- /**
- * Decodes one complete SSL/TLS record provided in the source buffer.
- * If decoded record contained application data, this data will
- * be placed in the destination buffers.
- * For more information about TLS record fragmentation see
- * TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
- * @param src source buffer containing SSL/TLS record.
- * @param dsts destination buffers to place received application data.
- * @see javax.net.ssl.SSLEngine#unwrap(ByteBuffer,ByteBuffer[],int,int)
- * method documentation for more information
- */
- @Override
- public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts,
- int offset, int length) throws SSLException {
- if (engine_was_shutteddown) {
- return new SSLEngineResult(SSLEngineResult.Status.CLOSED,
- SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
- }
- if ((src == null) || (dsts == null)) {
- throw new IllegalStateException(
- "Some of the input parameters are null");
- }
-
- if (!handshake_started) {
- beginHandshake();
- }
-
- SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
- // If is is initial handshake or connection closure stage,
- // check if this call was made in spite of handshake status
- if ((session == null || engine_was_closed) && (
- handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_WRAP) ||
- handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_TASK))) {
- return new SSLEngineResult(
- getEngineStatus(), handshakeStatus, 0, 0);
- }
-
- if (src.remaining() < recordProtocol.getMinRecordSize()) {
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_UNDERFLOW,
- getHandshakeStatus(), 0, 0);
- }
-
- try {
- src.mark();
- // check the destination buffers and count their capacity
- int capacity = 0;
- for (int i=offset; i<offset+length; i++) {
- if (dsts[i] == null) {
- throw new IllegalStateException(
- "Some of the input parameters are null");
- }
- if (dsts[i].isReadOnly()) {
- throw new ReadOnlyBufferException();
- }
- capacity += dsts[i].remaining();
- }
- if (capacity < recordProtocol.getDataSize(src.remaining())) {
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- getHandshakeStatus(), 0, 0);
- }
- recProtIS.setSourceBuffer(src);
- // unwrap the record contained in source buffer, pass it
- // to appropriate client protocol (alert, handshake, or app)
- // and retrieve the type of unwrapped data
- int type = recordProtocol.unwrap();
- // process the data and return the result
- switch (type) {
- case ContentType.HANDSHAKE:
- case ContentType.CHANGE_CIPHER_SPEC:
- if (handshakeProtocol.getStatus().equals(
- SSLEngineResult.HandshakeStatus.FINISHED)) {
- session = recordProtocol.getSession();
- }
- break;
- case ContentType.APPLICATION_DATA:
- break;
- case ContentType.ALERT:
- if (alertProtocol.isFatalAlert()) {
- alertProtocol.setProcessed();
- if (session != null) {
- session.invalidate();
- }
- String description = "Fatal alert received "
- + alertProtocol.getAlertDescription();
- shutdown();
- throw new SSLException(description);
- } else {
- if (logger != null) {
- logger.println("Warning allert has been received: "
- + alertProtocol.getAlertDescription());
- }
- switch(alertProtocol.getDescriptionCode()) {
- case AlertProtocol.CLOSE_NOTIFY:
- alertProtocol.setProcessed();
- close_notify_was_received = true;
- if (!close_notify_was_sent) {
- closeOutbound();
- closeInbound();
- } else {
- closeInbound();
- shutdown();
- }
- break;
- case AlertProtocol.NO_RENEGOTIATION:
- alertProtocol.setProcessed();
- if (session == null) {
- // message received during the initial
- // handshake
- throw new AlertException(
- AlertProtocol.HANDSHAKE_FAILURE,
- new SSLHandshakeException(
- "Received no_renegotiation "
- + "during the initial handshake"));
- } else {
- // just stop the handshake
- handshakeProtocol.stop();
- }
- break;
- default:
- alertProtocol.setProcessed();
- }
- }
- break;
- }
- return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(),
- recProtIS.consumed(),
- // place the app. data (if any) into the dest. buffers
- // and get the number of produced bytes:
- appData.placeTo(dsts, offset, length));
- } catch (BufferUnderflowException e) {
- // there was not enought data ource buffer to make complete packet
- src.reset();
- return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW,
- getHandshakeStatus(), 0, 0);
- } catch (AlertException e) {
- // fatal alert occured
- alertProtocol.alert(AlertProtocol.FATAL, e.getDescriptionCode());
- engine_was_closed = true;
- src.reset();
- if (session != null) {
- session.invalidate();
- }
- // shutdown work will be made after the alert will be sent
- // to another peer (by wrap method)
- throw e.getReason();
- } catch (SSLException e) {
- throw e;
- } catch (IOException e) {
- alertProtocol.alert(AlertProtocol.FATAL,
- AlertProtocol.INTERNAL_ERROR);
- engine_was_closed = true;
- // shutdown work will be made after the alert will be sent
- // to another peer (by wrap method)
- throw new SSLException(e.getMessage());
- }
- }
-
- /**
- * Encodes the application data into SSL/TLS record. If handshake status
- * of the engine differs from NOT_HANDSHAKING the operation can work
- * without consuming of the source data.
- * For more information about TLS record fragmentation see
- * TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
- * @param srcs the source buffers with application data to be encoded
- * into SSL/TLS record.
- * @param offset the offset in the destination buffers array pointing to
- * the first buffer with the source data.
- * @param len specifies the maximum number of buffers to be procesed.
- * @param dst the destination buffer where encoded data will be placed.
- * @see javax.net.ssl.SSLEngine#wrap(ByteBuffer[],int,int,ByteBuffer) method
- * documentation for more information
- */
- @Override
- public SSLEngineResult wrap(ByteBuffer[] srcs, int offset,
- int len, ByteBuffer dst) throws SSLException {
- if (engine_was_shutteddown) {
- return new SSLEngineResult(SSLEngineResult.Status.CLOSED,
- SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
- }
- if ((srcs == null) || (dst == null)) {
- throw new IllegalStateException(
- "Some of the input parameters are null");
- }
- if (dst.isReadOnly()) {
- throw new ReadOnlyBufferException();
- }
-
- if (!handshake_started) {
- beginHandshake();
- }
-
- SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
- // If it is an initial handshake or connection closure stage,
- // check if this call was made in spite of handshake status
- if ((session == null || engine_was_closed) && (
- handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_UNWRAP) ||
- handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_TASK))) {
- return new SSLEngineResult(
- getEngineStatus(), handshakeStatus, 0, 0);
- }
-
- int capacity = dst.remaining();
- int produced = 0;
-
- if (alertProtocol.hasAlert()) {
- // we have an alert to be sent
- if (capacity < recordProtocol.getRecordSize(2)) {
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, 0, 0);
- }
- byte[] alert_data = alertProtocol.wrap();
- // place the alert record into destination
- dst.put(alert_data);
- if (alertProtocol.isFatalAlert()) {
- alertProtocol.setProcessed();
- if (session != null) {
- session.invalidate();
- }
- // fatal alert has been sent, so shut down the engine
- shutdown();
- return new SSLEngineResult(
- SSLEngineResult.Status.CLOSED,
- SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
- 0, alert_data.length);
- } else {
- alertProtocol.setProcessed();
- // check if the works on this engine have been done
- if (close_notify_was_sent && close_notify_was_received) {
- shutdown();
- return new SSLEngineResult(SSLEngineResult.Status.CLOSED,
- SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING,
- 0, alert_data.length);
- }
- return new SSLEngineResult(
- getEngineStatus(),
- getHandshakeStatus(),
- 0, alert_data.length);
- }
- }
-
- if (capacity < recordProtocol.getMinRecordSize()) {
- if (logger != null) {
- logger.println("Capacity of the destination("
- +capacity+") < MIN_PACKET_SIZE("
- +recordProtocol.getMinRecordSize()+")");
- }
- return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, 0, 0);
- }
-
- try {
- if (!handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.NEED_WRAP)) {
- // so we wraps application data
- dataStream.setSourceBuffers(srcs, offset, len);
- if ((capacity < SSLRecordProtocol.MAX_SSL_PACKET_SIZE) &&
- (capacity < recordProtocol.getRecordSize(
- dataStream.available()))) {
- if (logger != null) {
- logger.println("The destination buffer("
- +capacity+") can not take the resulting packet("
- + recordProtocol.getRecordSize(
- dataStream.available())+")");
- }
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, 0, 0);
- }
- if (remaining_wrapped_data == null) {
- remaining_wrapped_data =
- recordProtocol.wrap(ContentType.APPLICATION_DATA,
- dataStream);
- }
- if (capacity < remaining_wrapped_data.length) {
- // It should newer happen because we checked the destination
- // buffer size, but there is a possibility
- // (if dest buffer was filled outside)
- // so we just remember the data into remaining_wrapped_data
- // and will enclose it during the the next call
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, dataStream.consumed(), 0);
- } else {
- dst.put(remaining_wrapped_data);
- produced = remaining_wrapped_data.length;
- remaining_wrapped_data = null;
- return new SSLEngineResult(getEngineStatus(),
- handshakeStatus, dataStream.consumed(), produced);
- }
- } else {
- if (remaining_hsh_data == null) {
- remaining_hsh_data = handshakeProtocol.wrap();
- }
- if (capacity < remaining_hsh_data.length) {
- // It should newer happen because we checked the destination
- // buffer size, but there is a possibility
- // (if dest buffer was filled outside)
- // so we just remember the data into remaining_hsh_data
- // and will enclose it during the the next call
- return new SSLEngineResult(
- SSLEngineResult.Status.BUFFER_OVERFLOW,
- handshakeStatus, 0, 0);
- } else {
- dst.put(remaining_hsh_data);
- produced = remaining_hsh_data.length;
- remaining_hsh_data = null;
-
- handshakeStatus = handshakeProtocol.getStatus();
- if (handshakeStatus.equals(
- SSLEngineResult.HandshakeStatus.FINISHED)) {
- session = recordProtocol.getSession();
- }
- }
- return new SSLEngineResult(
- getEngineStatus(), getHandshakeStatus(), 0, produced);
- }
- } catch (AlertException e) {
- // fatal alert occured
- alertProtocol.alert(AlertProtocol.FATAL, e.getDescriptionCode());
- engine_was_closed = true;
- if (session != null) {
- session.invalidate();
- }
- // shutdown work will be made after the alert will be sent
- // to another peer (by wrap method)
- throw e.getReason();
- }
- }
-
- // Shutdownes the engine and makes all cleanup work.
- private void shutdown() {
- engine_was_closed = true;
- engine_was_shutteddown = true;
- isOutboundDone = true;
- isInboundDone = true;
- if (handshake_started) {
- alertProtocol.shutdown();
- alertProtocol = null;
- handshakeProtocol.shutdown();
- handshakeProtocol = null;
- recordProtocol.shutdown();
- recordProtocol = null;
- }
- }
-
-
- private SSLEngineResult.Status getEngineStatus() {
- return (engine_was_closed)
- ? SSLEngineResult.Status.CLOSED
- : SSLEngineResult.Status.OK;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java
deleted file mode 100644
index b2501a7..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLInputStream.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * This class is a base for all input stream classes used
- * in protocol implementation. It extends an InputStream with
- * some additional read methods allowing to read TLS specific
- * data types such as uint8, uint32 etc (see TLS v 1 specification
- * at http://www.ietf.org/rfc/rfc2246.txt).
- */
-public abstract class SSLInputStream extends InputStream {
-
- @Override
- public abstract int available() throws IOException;
-
- /**
- * Reads the following byte value. Note that in the case of
- * reaching of the end of the data this methods throws the
- * exception, not return -1. The type of exception depends
- * on implementation. It was done for simplifying and speeding
- * up of processing of such cases.
- * @see org.apache.harmony.xnet.provider.jsse.SSLStreamedInput#read()
- * @see org.apache.harmony.xnet.provider.jsse.SSLBufferedInput#read()
- * @see org.apache.harmony.xnet.provider.jsse.HandshakeIODataStream#read()
- */
- @Override
- public abstract int read() throws IOException;
-
- @Override
- public long skip(long n) throws IOException {
- long skept = n;
- while (n > 0) {
- read();
- n--;
- }
- return skept;
- }
-
- /**
- * Reads and returns uint8 value.
- */
- public int readUint8() throws IOException {
- return read() & 0x00FF;
- }
-
- /**
- * Reads and returns uint16 value.
- */
- public int readUint16() throws IOException {
- return (read() << 8) | (read() & 0x00FF);
- }
-
- /**
- * Reads and returns uint24 value.
- */
- public int readUint24() throws IOException {
- return (read() << 16) | (read() << 8) | (read() & 0x00FF);
- }
-
- /**
- * Reads and returns uint32 value.
- */
- public long readUint32() throws IOException {
- return (read() << 24) | (read() << 16)
- | (read() << 8) | (read() & 0x00FF);
- }
-
- /**
- * Reads and returns uint64 value.
- */
- public long readUint64() throws IOException {
- // BEGIN android-changed
- long hi = readUint32();
- long lo = readUint32();
- return (hi << 32) | lo;
- // END android-changed
- }
-
- /**
- * Returns the vector of opaque values of specified length;
- * @param length - the length of the vector to be read.
- * @return the read data
- * @throws IOException if read operation could not be finished.
- */
- public byte[] read(int length) throws IOException {
- byte[] res = new byte[length];
- for (int i=0; i<length; i++) {
- res[i] = (byte) read();
- }
- return res;
- }
-
- @Override
- public int read(byte[] b, int off, int len) throws IOException {
- int read_b;
- int i = 0;
- do {
- if ((read_b = read()) == -1) {
- return (i == 0) ? -1 : i;
- }
- b[off+i] = (byte) read_b;
- i++;
- } while ((available() != 0) && (i<len));
- return i;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParameters.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParameters.java
deleted file mode 100644
index 9c6f0a0..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLParameters.java
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyManagementException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.SecureRandom;
-import java.security.UnrecoverableKeyException;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-
-import javax.net.ssl.KeyManager;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLException;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactory;
-import javax.net.ssl.X509KeyManager;
-import javax.net.ssl.X509TrustManager;
-
-import org.apache.harmony.security.provider.cert.X509CertImpl;
-
-/**
- * The instances of this class incapsulate all the info
- * about enabled cipher suites and protocols,
- * as well as the information about client/server mode of
- * ssl socket, whether it require/want client authentication or not,
- * and controls whether new SSL sessions may be established by this
- * socket or not.
- */
-// BEGIN android-changed
-public class SSLParameters implements Cloneable {
-// END android-changed
-
- // default source of authentication keys
- private static X509KeyManager defaultKeyManager;
- // default source of authentication trust decisions
- private static X509TrustManager defaultTrustManager;
- // default source of random numbers
- private static SecureRandom defaultSecureRandom;
- // default SSL parameters
- private static SSLParameters defaultParameters;
-
- // client session context contains the set of reusable
- // client-side SSL sessions
-// BEGIN android-changed
- private final ClientSessionContext clientSessionContext;
- // server session context contains the set of reusable
- // server-side SSL sessions
- private final ServerSessionContext serverSessionContext;
-// END android-changed
- // source of authentication keys
- private X509KeyManager keyManager;
- // source of authentication trust decisions
- private X509TrustManager trustManager;
- // source of random numbers
- private SecureRandom secureRandom;
-
- // cipher suites available for SSL connection
- // BEGIN android-changed
- private CipherSuite[] enabledCipherSuites;
- // END android-changed
- // string representations of available cipher suites
- private String[] enabledCipherSuiteNames = null;
-
- // protocols available for SSL connection
- private String[] enabledProtocols = ProtocolVersion.supportedProtocols;
-
- // if the peer with this parameters tuned to work in client mode
- private boolean client_mode = true;
- // if the peer with this parameters tuned to require client authentication
- private boolean need_client_auth = false;
- // if the peer with this parameters tuned to request client authentication
- private boolean want_client_auth = false;
- // if the peer with this parameters allowed to cteate new SSL session
- private boolean enable_session_creation = true;
-
-// BEGIN android-changed
- protected CipherSuite[] getEnabledCipherSuitesMember() {
- if (enabledCipherSuites == null) this.enabledCipherSuites = CipherSuite.defaultCipherSuites;
- return enabledCipherSuites;
- }
-// END android-changed
-
- /**
- * Initializes the parameters. Naturally this constructor is used
- * in SSLContextImpl.engineInit method which dirrectly passes its
- * parameters. In other words this constructor holds all
- * the functionality provided by SSLContext.init method.
- * See {@link javax.net.ssl.SSLContext#init(KeyManager[],TrustManager[],
- * SecureRandom)} for more information
- */
- protected SSLParameters(KeyManager[] kms, TrustManager[] tms,
-// BEGIN android-changed
- SecureRandom sr, SSLClientSessionCache clientCache,
- SSLServerSessionCache serverCache)
- throws KeyManagementException {
- this.serverSessionContext
- = new ServerSessionContext(NativeCrypto.SSL_CTX_new(), serverCache);
- this.clientSessionContext
- = new ClientSessionContext(NativeCrypto.SSL_CTX_new(), clientCache);
-// END android-changed
- try {
- // initialize key manager
- boolean initialize_default = false;
- // It's not described by the spec of SSLContext what should happen
- // if the arrays of length 0 are specified. This implementation
- // behave as for null arrays (i.e. use installed security providers)
- if ((kms == null) || (kms.length == 0)) {
- if (defaultKeyManager == null) {
- KeyManagerFactory kmf = KeyManagerFactory.getInstance(
- KeyManagerFactory.getDefaultAlgorithm());
- kmf.init(null, null);
- kms = kmf.getKeyManagers();
- // tell that we are trying to initialize defaultKeyManager
- initialize_default = true;
- } else {
- keyManager = defaultKeyManager;
- }
- }
- if (keyManager == null) { // was not initialized by default
- for (int i = 0; i < kms.length; i++) {
- if (kms[i] instanceof X509KeyManager) {
- keyManager = (X509KeyManager)kms[i];
- break;
- }
- }
- if (keyManager == null) {
- throw new KeyManagementException("No X509KeyManager found");
- }
- if (initialize_default) {
- // found keyManager is default key manager
- defaultKeyManager = keyManager;
- }
- }
-
- // initialize trust manager
- initialize_default = false;
- if ((tms == null) || (tms.length == 0)) {
- if (defaultTrustManager == null) {
- TrustManagerFactory tmf = TrustManagerFactory
- .getInstance(TrustManagerFactory.getDefaultAlgorithm());
- tmf.init((KeyStore)null);
- tms = tmf.getTrustManagers();
- initialize_default = true;
- } else {
- trustManager = defaultTrustManager;
- }
- }
- if (trustManager == null) { // was not initialized by default
- for (int i = 0; i < tms.length; i++) {
- if (tms[i] instanceof X509TrustManager) {
- trustManager = (X509TrustManager)tms[i];
- break;
- }
- }
- if (trustManager == null) {
- throw new KeyManagementException("No X509TrustManager found");
- }
- if (initialize_default) {
- // found trustManager is default trust manager
- defaultTrustManager = trustManager;
-// BEGIN android-added
- if (trustManager instanceof TrustManagerImpl) {
- ((TrustManagerImpl) trustManager).indexTrustAnchors();
- }
-// END android-added
- }
- }
- } catch (NoSuchAlgorithmException e) {
- throw new KeyManagementException(e);
- } catch (KeyStoreException e) {
- throw new KeyManagementException(e);
- } catch (UnrecoverableKeyException e) {
- throw new KeyManagementException(e);
-// BEGIN android-added
- } catch (CertificateEncodingException e) {
- throw new KeyManagementException(e);
- } catch (InvalidAlgorithmParameterException e) {
- throw new KeyManagementException(e);
-// END android-added
- }
- // initialize secure random
- // BEGIN android-removed
- // if (sr == null) {
- // if (defaultSecureRandom == null) {
- // defaultSecureRandom = new SecureRandom();
- // }
- // secureRandom = defaultSecureRandom;
- // } else {
- // secureRandom = sr;
- // }
- // END android-removed
- // BEGIN android-added
- // We simply use the SecureRandom passed in by the caller. If it's
- // null, we don't replace it by a new instance. The native code below
- // then directly accesses /dev/urandom. Not the most elegant solution,
- // but faster than going through the SecureRandom object.
- secureRandom = sr;
- // END android-added
- }
-
- protected static SSLParameters getDefault() throws KeyManagementException {
- if (defaultParameters == null) {
-// BEGIN android-changed
- defaultParameters = new SSLParameters(null, null, null, null, null);
-// END android-changed
- }
- return (SSLParameters) defaultParameters.clone();
- }
-
- /**
- * @return server session context
- */
-// BEGIN android-changed
- protected ServerSessionContext getServerSessionContext() {
-// END android-changed
- return serverSessionContext;
- }
-
- /**
- * @return client session context
- */
-// BEGIN android-changed
- protected ClientSessionContext getClientSessionContext() {
-// END android-changed
- return clientSessionContext;
- }
-
- /**
- * @return key manager
- */
- protected X509KeyManager getKeyManager() {
- return keyManager;
- }
-
- /**
- * @return trust manager
- */
- protected X509TrustManager getTrustManager() {
- return trustManager;
- }
-
- /**
- * @return secure random
- */
- protected SecureRandom getSecureRandom() {
- // BEGIN android-removed
- // return secureRandom;
- // END android-removed
- // BEGIN android-added
- if (secureRandom != null) return secureRandom;
- if (defaultSecureRandom == null)
- {
- defaultSecureRandom = new SecureRandom();
- }
- secureRandom = defaultSecureRandom;
- // END android-added
- return secureRandom;
- }
-
- // BEGIN android-added
- /**
- * @return the secure random member reference, even it is null
- */
- protected SecureRandom getSecureRandomMember() {
- return secureRandom;
- }
- // END android-added
-
- /**
- * @return the names of enabled cipher suites
- */
- protected String[] getEnabledCipherSuites() {
- if (enabledCipherSuiteNames == null) {
- // BEGIN android-added
- CipherSuite[] enabledCipherSuites = getEnabledCipherSuitesMember();
- // END android-added
- enabledCipherSuiteNames = new String[enabledCipherSuites.length];
- for (int i = 0; i< enabledCipherSuites.length; i++) {
- enabledCipherSuiteNames[i] = enabledCipherSuites[i].getName();
- }
- }
- return enabledCipherSuiteNames.clone();
- }
-
- /**
- * Sets the set of available cipher suites for use in SSL connection.
- * @param suites: String[]
- * @return
- */
- protected void setEnabledCipherSuites(String[] suites) {
- if (suites == null) {
- throw new IllegalArgumentException("Provided parameter is null");
- }
- CipherSuite[] cipherSuites = new CipherSuite[suites.length];
- for (int i=0; i<suites.length; i++) {
- cipherSuites[i] = CipherSuite.getByName(suites[i]);
- if (cipherSuites[i] == null || !cipherSuites[i].supported) {
- throw new IllegalArgumentException(suites[i] +
- " is not supported.");
- }
- }
- enabledCipherSuites = cipherSuites;
- enabledCipherSuiteNames = suites;
- }
-
- /**
- * @return the set of enabled protocols
- */
- protected String[] getEnabledProtocols() {
- return enabledProtocols.clone();
- }
-
- /**
- * Sets the set of available protocols for use in SSL connection.
- * @param protocols String[]
- */
- protected void setEnabledProtocols(String[] protocols) {
- if (protocols == null) {
- throw new IllegalArgumentException("Provided parameter is null");
- }
- for (int i=0; i<protocols.length; i++) {
- if (!ProtocolVersion.isSupported(protocols[i])) {
- throw new IllegalArgumentException("Protocol " + protocols[i] +
- " is not supported.");
- }
- }
- enabledProtocols = protocols;
- }
-
- /**
- * Tunes the peer holding this parameters to work in client mode.
- * @param mode if the peer is configured to work in client mode
- */
- protected void setUseClientMode(boolean mode) {
- client_mode = mode;
- }
-
- /**
- * Returns the value indicating if the parameters configured to work
- * in client mode.
- */
- protected boolean getUseClientMode() {
- return client_mode;
- }
-
- /**
- * Tunes the peer holding this parameters to require client authentication
- */
- protected void setNeedClientAuth(boolean need) {
- need_client_auth = need;
- // reset the want_client_auth setting
- want_client_auth = false;
- }
-
- /**
- * Returns the value indicating if the peer with this parameters tuned
- * to require client authentication
- */
- protected boolean getNeedClientAuth() {
- return need_client_auth;
- }
-
- /**
- * Tunes the peer holding this parameters to request client authentication
- */
- protected void setWantClientAuth(boolean want) {
- want_client_auth = want;
- // reset the need_client_auth setting
- need_client_auth = false;
- }
-
- /**
- * Returns the value indicating if the peer with this parameters
- * tuned to request client authentication
- * @return
- */
- protected boolean getWantClientAuth() {
- return want_client_auth;
- }
-
- /**
- * Allows/disallows the peer holding this parameters to
- * create new SSL session
- */
- protected void setEnableSessionCreation(boolean flag) {
- enable_session_creation = flag;
- }
-
- /**
- * Returns the value indicating if the peer with this parameters
- * allowed to cteate new SSL session
- */
- protected boolean getEnableSessionCreation() {
- return enable_session_creation;
- }
-
- /**
- * Returns the clone of this object.
- * @return the clone.
- */
- @Override
- protected Object clone() {
-// BEGIN android-changed
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e);
- }
-// END android-changed
- }
-
- /**
- * Gets the default trust manager.
- *
- * TODO: Move this to a published API under dalvik.system.
- */
- public static X509TrustManager getDefaultTrustManager() {
- return defaultTrustManager;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java
deleted file mode 100644
index 423a817..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLRecordProtocol.java
+++ /dev/null
@@ -1,482 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.AlertException;
-import org.apache.harmony.xnet.provider.jsse.SSLSessionImpl;
-import org.apache.harmony.xnet.provider.jsse.SSLInputStream;
-
-import java.io.IOException;
-import javax.net.ssl.SSLProtocolException;
-
-/**
- * This class performs functionality dedicated to SSL record layer.
- * It unpacks and routes income data to the appropriate
- * client protocol (handshake, alert, application data protocols)
- * and packages outcome data into SSL/TLS records.
- * Initially created object has null connection state and does not
- * perform any cryptography computations over the income/outcome data.
- * After handshake protocol agreed upon security parameters they are placed
- * into SSLSessionImpl object and available for record protocol as
- * pending session. The order of setting up of the pending session
- * as an active session differs for client and server modes.
- * So for client mode the parameters are provided by handshake protocol
- * during retrieving of change_cipher_spec message to be sent (by calling of
- * getChangeCipherSpecMesage method).
- * For server side mode record protocol retrieves the parameters from
- * handshake protocol after receiving of client's change_cipher_spec message.
- * After the pending session has been setted up as a curent session,
- * new connectin state object is created and used for encryption/decryption
- * of the messages.
- * Among with base functionality this class provides the information about
- * constrains on the data length, and information about correspondance
- * of plain and encrypted data lengths.
- * For more information on TLS v1 see http://www.ietf.org/rfc/rfc2246.txt,
- * on SSL v3 see http://wp.netscape.com/eng/ssl3,
- * on SSL v2 see http://wp.netscape.com/eng/security/SSL_2.html.
- */
-public class SSLRecordProtocol {
-
- /**
- * Maximum length of allowed plain data fragment
- * as specified by TLS specification.
- */
- protected static int MAX_DATA_LENGTH = 16384; // 2^14
- /**
- * Maximum length of allowed compressed data fragment
- * as specified by TLS specification.
- */
- protected static int MAX_COMPRESSED_DATA_LENGTH
- = MAX_DATA_LENGTH + 1024;
- /**
- * Maximum length of allowed ciphered data fragment
- * as specified by TLS specification.
- */
- protected static int MAX_CIPHERED_DATA_LENGTH
- = MAX_COMPRESSED_DATA_LENGTH + 1024;
- /**
- * Maximum length of ssl record. It is counted as:
- * type(1) + version(2) + length(2) + MAX_CIPHERED_DATA_LENGTH
- */
- protected static int MAX_SSL_PACKET_SIZE
- = MAX_CIPHERED_DATA_LENGTH + 5;
- // the SSL session used for connection
- private SSLSessionImpl session;
- // protocol version of the connection
- private byte[] version;
- // input stream of record protocol
- private SSLInputStream in;
- // handshake protocol object to which handshaking data will be transmitted
- private HandshakeProtocol handshakeProtocol;
- // alert protocol to indicate alerts occured/received
- private AlertProtocol alertProtocol;
- // application data object to which application data will be transmitted
- private org.apache.harmony.xnet.provider.jsse.Appendable appData;
- // connection state holding object
- private ConnectionState
- activeReadState, activeWriteState, pendingConnectionState;
-
- // logger
- private Logger.Stream logger = Logger.getStream("record");
-
- // flag indicating if session object has been changed after
- // handshake phase (to distinguish session pending state)
- private boolean sessionWasChanged = false;
-
- // change cipher spec message content
- private static final byte[] change_cipher_spec_byte = new byte[] {1};
-
- /**
- * Creates an instance of record protocol and tunes
- * up the client protocols to use ut.
- * @param handshakeProtocol: HandshakeProtocol
- * @param alertProtocol: AlertProtocol
- * @param in: SSLInputStream
- * @param appData: Appendable
- */
- protected SSLRecordProtocol(HandshakeProtocol handshakeProtocol,
- AlertProtocol alertProtocol,
- SSLInputStream in,
- Appendable appData) {
- this.handshakeProtocol = handshakeProtocol;
- this.handshakeProtocol.setRecordProtocol(this);
- this.alertProtocol = alertProtocol;
- this.alertProtocol.setRecordProtocol(this);
- this.in = in;
- this.appData = appData;
- }
-
- /**
- * Returns the session obtained during the handshake negotiation.
- * If the handshake process was not compleated, method returns null.
- * @return the session in effect.
- */
- protected SSLSessionImpl getSession() {
- return session;
- }
-
- /**
- * Returns the minimum possible length of the SSL record.
- * @return
- */
- protected int getMinRecordSize() {
- return (activeReadState == null)
- ? 6 // type + version + length + 1 byte of data
- : 5 + activeReadState.getMinFragmentSize();
- }
-
- /**
- * Returns the record length for the specified incoming data length.
- * If actual resulting record length is greater than
- * MAX_CIPHERED_DATA_LENGTH, MAX_CIPHERED_DATA_LENGTH is returned.
- */
- protected int getRecordSize(int data_size) {
- if (activeWriteState == null) {
- return 5+data_size; // type + version + length + data_size
- } else {
- int res = 5 + activeWriteState.getFragmentSize(data_size);
- return (res > MAX_CIPHERED_DATA_LENGTH)
- ? MAX_CIPHERED_DATA_LENGTH // so the source data should be
- // splitted into several packets
- : res;
- }
- }
-
- /**
- * Returns the upper bound of length of data containing in the record with
- * specified length.
- * If the provided record_size is greater or equal to
- * MAX_CIPHERED_DATA_LENGTH the returned value will be
- * MAX_DATA_LENGTH
- * counted as for data with
- * MAX_CIPHERED_DATA_LENGTH length.
- */
- protected int getDataSize(int record_size) {
- record_size -= 5; // - (type + version + length + data_size)
- if (record_size > MAX_CIPHERED_DATA_LENGTH) {
- // the data of such size consists of the several packets
- return MAX_DATA_LENGTH;
- }
- if (activeReadState == null) {
- return record_size;
- }
- return activeReadState.getContentSize(record_size);
- }
-
- /**
- * Depending on the Connection State (Session) encrypts and compress
- * the provided data, and packs it into TLSCiphertext structure.
- * @param content_type: int
- * @param fragment: byte[]
- * @return ssl packet created over the current connection state
- */
- protected byte[] wrap(byte content_type, DataStream dataStream) {
- byte[] fragment = dataStream.getData(MAX_DATA_LENGTH);
- return wrap(content_type, fragment, 0, fragment.length);
- }
-
- /**
- * Depending on the Connection State (Session) encrypts and compress
- * the provided data, and packs it into TLSCiphertext structure.
- * @param content_type: int
- * @param fragment: byte[]
- * @return ssl packet created over the current connection state
- */
- protected byte[] wrap(byte content_type,
- byte[] fragment, int offset, int len) {
- if (logger != null) {
- logger.println("SSLRecordProtocol.wrap: TLSPlaintext.fragment["
- +len+"]:");
- logger.print(fragment, offset, len);
- }
- if (len > MAX_DATA_LENGTH) {
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException(
- "The provided chunk of data is too big: " + len
- + " > MAX_DATA_LENGTH == "+MAX_DATA_LENGTH));
- }
- byte[] ciphered_fragment = fragment;
- if (activeWriteState != null) {
- ciphered_fragment =
- activeWriteState.encrypt(content_type, fragment, offset, len);
- if (ciphered_fragment.length > MAX_CIPHERED_DATA_LENGTH) {
- throw new AlertException(
- AlertProtocol.INTERNAL_ERROR,
- new SSLProtocolException(
- "The ciphered data increased more than on 1024 bytes"));
- }
- if (logger != null) {
- logger.println("SSLRecordProtocol.wrap: TLSCiphertext.fragment["
- +ciphered_fragment.length+"]:");
- logger.print(ciphered_fragment);
- }
- }
- return packetize(content_type, version, ciphered_fragment);
- }
-
- private byte[] packetize(byte type, byte[] version, byte[] fragment) {
- byte[] buff = new byte[5+fragment.length];
- buff[0] = type;
- if (version != null) {
- buff[1] = version[0];
- buff[2] = version[1];
- } else {
- buff[1] = 3;
- buff[2] = 1;
- }
- buff[3] = (byte) ((0x00FF00 & fragment.length) >> 8);
- buff[4] = (byte) (0x0000FF & fragment.length);
- System.arraycopy(fragment, 0, buff, 5, fragment.length);
- return buff;
- }
-
- /**
- * Set the ssl session to be used after sending the changeCipherSpec message
- * @param session: SSLSessionImpl
- */
- private void setSession(SSLSessionImpl session) {
- if (!sessionWasChanged) {
- // session was not changed for current handshake process
- if (logger != null) {
- logger.println("SSLRecordProtocol.setSession: Set pending session");
- logger.println(" cipher name: " + session.getCipherSuite());
- }
- this.session = session;
- // create new connection state
- pendingConnectionState = ((version == null) || (version[1] == 1))
- ? (ConnectionState) new ConnectionStateTLS(getSession())
- : (ConnectionState) new ConnectionStateSSLv3(getSession());
- sessionWasChanged = true;
- } else {
- // wait for rehandshaking's session
- sessionWasChanged = false;
- }
- }
-
- /**
- * Returns the change cipher spec message to be sent to another peer.
- * The pending connection state will be built on the base of provided
- * session object
- * The calling of this method triggers pending write connection state to
- * be active.
- * @return ssl record containing the "change cipher spec" message.
- */
- protected byte[] getChangeCipherSpecMesage(SSLSessionImpl session) {
- // make change_cipher_spec_message:
- byte[] change_cipher_spec_message;
- if (activeWriteState == null) {
- change_cipher_spec_message = new byte[] {
- ContentType.CHANGE_CIPHER_SPEC, version[0],
- version[1], 0, 1, 1
- };
- } else {
- change_cipher_spec_message =
- packetize(ContentType.CHANGE_CIPHER_SPEC, version,
- activeWriteState.encrypt(ContentType.CHANGE_CIPHER_SPEC,
- change_cipher_spec_byte, 0, 1));
- }
- setSession(session);
- activeWriteState = pendingConnectionState;
- if (logger != null) {
- logger.println("SSLRecordProtocol.getChangeCipherSpecMesage");
- logger.println("activeWriteState = pendingConnectionState");
- logger.print(change_cipher_spec_message);
- }
- return change_cipher_spec_message;
- }
-
- /**
- * Retrieves the fragment field of TLSCiphertext, and than
- * depending on the established Connection State
- * decrypts and decompresses it. The following structure is expected
- * on the input at the moment of the call:
- *
- * struct {
- * ContentType type;
- * ProtocolVersion version;
- * uint16 length;
- * select (CipherSpec.cipher_type) {
- * case stream: GenericStreamCipher;
- * case block: GenericBlockCipher;
- * } fragment;
- * } TLSCiphertext;
- *
- * (as specified by RFC 2246, TLS v1 Protocol specification)
- *
- * In addition this method can recognize SSLv2 hello message which
- * are often used to establish the SSL/TLS session.
- *
- * @throws IOException if some io errors have been occured
- * @throws EndOfSourceException if underlying input stream
- * has ran out of data.
- * @throws EndOfBufferException if there was not enought data
- * to build complete ssl packet.
- * @return the type of unwrapped message.
- */
- protected int unwrap() throws IOException {
- if (logger != null) {
- logger.println("SSLRecordProtocol.unwrap: BEGIN [");
- }
- int type = in.readUint8();
- if ((type < ContentType.CHANGE_CIPHER_SPEC)
- || (type > ContentType.APPLICATION_DATA)) {
- if (logger != null) {
- logger.println("Non v3.1 message type:" + type);
- }
- if (type >= 0x80) {
- // it is probably SSL v2 client_hello message
- // (see SSL v2 spec at:
- // http://wp.netscape.com/eng/security/SSL_2.html)
- int length = (type & 0x7f) << 8 | in.read();
- byte[] fragment = in.read(length);
- handshakeProtocol.unwrapSSLv2(fragment);
- if (logger != null) {
- logger.println(
- "SSLRecordProtocol:unwrap ] END, SSLv2 type");
- }
- return ContentType.HANDSHAKE;
- }
- throw new AlertException(AlertProtocol.UNEXPECTED_MESSAGE,
- new SSLProtocolException(
- "Unexpected message type has been received: "+type));
- }
- if (logger != null) {
- logger.println("Got the message of type: " + type);
- }
- if (version != null) {
- if ((in.read() != version[0])
- || (in.read() != version[1])) {
- throw new AlertException(AlertProtocol.UNEXPECTED_MESSAGE,
- new SSLProtocolException(
- "Unexpected message type has been received: " +
- type));
- }
- } else {
- in.skip(2); // just skip the version number
- }
- int length = in.readUint16();
- if (logger != null) {
- logger.println("TLSCiphertext.fragment["+length+"]: ...");
- }
- if (length > MAX_CIPHERED_DATA_LENGTH) {
- throw new AlertException(AlertProtocol.RECORD_OVERFLOW,
- new SSLProtocolException(
- "Received message is too big."));
- }
- byte[] fragment = in.read(length);
- if (logger != null) {
- logger.print(fragment);
- }
- if (activeReadState != null) {
- fragment = activeReadState.decrypt((byte) type, fragment);
- if (logger != null) {
- logger.println("TLSPlaintext.fragment:");
- logger.print(fragment);
- }
- }
- if (fragment.length > MAX_DATA_LENGTH) {
- throw new AlertException(AlertProtocol.DECOMPRESSION_FAILURE,
- new SSLProtocolException(
- "Decompressed plain data is too big."));
- }
- switch (type) {
- case ContentType.CHANGE_CIPHER_SPEC:
- // notify handshake protocol:
- handshakeProtocol.receiveChangeCipherSpec();
- setSession(handshakeProtocol.getSession());
- // change cipher spec message has been received, so:
- if (logger != null) {
- logger.println("activeReadState = pendingConnectionState");
- }
- activeReadState = pendingConnectionState;
- break;
- case ContentType.ALERT:
- alert(fragment[0], fragment[1]);
- break;
- case ContentType.HANDSHAKE:
- handshakeProtocol.unwrap(fragment);
- break;
- case ContentType.APPLICATION_DATA:
- if (logger != null) {
- logger.println(
- "TLSCiphertext.unwrap: APP DATA["+length+"]:");
- logger.println(new String(fragment));
- }
- appData.append(fragment);
- break;
- default:
- throw new AlertException(AlertProtocol.UNEXPECTED_MESSAGE,
- new SSLProtocolException(
- "Unexpected message type has been received: " +
- type));
- }
- if (logger != null) {
- logger.println("SSLRecordProtocol:unwrap ] END, type: " + type);
- }
- return type;
- }
-
- /**
- * Passes the alert information to the alert protocol.
- * @param level: byte
- * @param description: byte
- */
- protected void alert(byte level, byte description) {
- if (logger != null) {
- logger.println("SSLRecordProtocol.allert: "+level+" "+description);
- }
- alertProtocol.alert(level, description);
- }
-
- /**
- * Sets up the SSL version used in this connection.
- * This method is calling from the hanshake protocol after
- * it becomes known witch protocol version will be used.
- * @param ver: byte[]
- * @return
- */
- protected void setVersion(byte[] ver) {
- this.version = ver;
- }
-
- /**
- * Shutdownes the protocol. It will be impossiblke to use the instance
- * after the calling of this method.
- */
- protected void shutdown() {
- session = null;
- version = null;
- in = null;
- handshakeProtocol = null;
- alertProtocol = null;
- appData = null;
- if (pendingConnectionState != null) {
- pendingConnectionState.shutdown();
- }
- pendingConnectionState = null;
- if (activeReadState != null) {
- activeReadState.shutdown();
- }
- activeReadState = null;
- if (activeReadState != null) {
- activeReadState.shutdown();
- }
- activeWriteState = null;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSessionCache.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSessionCache.java
deleted file mode 100644
index 32a0e72..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLServerSessionCache.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import javax.net.ssl.SSLSession;
-
-/**
- * A persistent {@link javax.net.ssl.SSLSession} cache used by
- * {@link javax.net.ssl.SSLSessionContext} to share server-side SSL sessions
- * across processes. For example, this cache enables one server to resume
- * a session started by a different server based on a session ID provided
- * by the client.
- *
- * <p>The {@code SSLSessionContext} implementation converts
- * {@code SSLSession}s into raw bytes and vice versa. The exact makeup of the
- * session data is dependent upon the caller's implementation and is opaque to
- * the {@code SSLServerSessionCache} implementation.
- */
-public interface SSLServerSessionCache {
-
- /**
- * Gets the session data for given session ID.
- *
- * @param id from {@link javax.net.ssl.SSLSession#getId()}
- * @return the session data or null if none is cached
- * @throws NullPointerException if id is null
- */
- public byte[] getSessionData(byte[] id);
-
- /**
- * Stores session data for the given session.
- *
- * @param session to cache data for
- * @param sessionData to cache
- * @throws NullPointerException if session or data is null
- */
- public void putSessionData(SSLSession session, byte[] sessionData);
-} \ No newline at end of file
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java
deleted file mode 100644
index 922de2b..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLSessionImpl.java
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.security.AccessControlContext;
-import java.security.AccessController;
-import java.security.Principal;
-import java.security.SecureRandom;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-import java.security.cert.X509Certificate;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Vector;
-
-import javax.net.ssl.SSLPeerUnverifiedException;
-import javax.net.ssl.SSLPermission;
-import javax.net.ssl.SSLSession;
-import javax.net.ssl.SSLSessionBindingEvent;
-import javax.net.ssl.SSLSessionBindingListener;
-import javax.net.ssl.SSLSessionContext;
-
-/**
- *
- * SSLSession implementation
- *
- * @see javax.net.ssl.SSLSession
- */
-public class SSLSessionImpl implements SSLSession, Cloneable {
-
- /**
- * Session object reporting an invalid cipher suite of "SSL_NULL_WITH_NULL_NULL"
- */
- public static final SSLSessionImpl NULL_SESSION = new SSLSessionImpl(null);
-
- /**
- * Container class for the 'value' map's keys.
- */
- private static final class ValueKey {
- final String name;
- final AccessControlContext acc;
-
- ValueKey(String name) {
- super();
- this.name = name;
- this.acc = AccessController.getContext();
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((acc == null) ? 0 : acc.hashCode());
- result = prime * result + ((name == null) ? 0 : name.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (!(obj instanceof ValueKey))
- return false;
- ValueKey other = (ValueKey) obj;
- if (acc == null) {
- if (other.acc != null)
- return false;
- } else if (!acc.equals(other.acc))
- return false;
- if (name == null) {
- if (other.name != null)
- return false;
- } else if (!name.equals(other.name))
- return false;
- return true;
- }
- }
-
- private long creationTime;
- private boolean isValid = true;
- private Map<ValueKey, Object> values = new HashMap<ValueKey, Object>();
-
- /**
- * ID of the session
- */
- byte[] id;
-
- /**
- * Last time the session was accessed
- */
- long lastAccessedTime;
-
- /**
- * Protocol used in the session
- */
- ProtocolVersion protocol;
-
- /**
- * CipherSuite used in the session
- */
- CipherSuite cipherSuite;
-
- /**
- * Context of the session
- */
-// BEGIN android-changed
- SSLSessionContext context;
-// END android-changed
-
- /**
- * certificates were sent to the peer
- */
- X509Certificate[] localCertificates;
-
- /**
- * Peer certificates
- */
- X509Certificate[] peerCertificates;
-
- /**
- * Peer host name
- */
- private String peerHost;
-
- /**
- * Peer port number
- */
- private int peerPort = -1;
-
- /**
- * Master secret
- */
- byte[] master_secret;
-
- /**
- * clientRandom
- */
- byte[] clientRandom;
-
- /**
- * serverRandom
- */
- byte[] serverRandom;
-
- /**
- * True if this entity is considered the server
- */
- final boolean isServer;
-
- /**
- * Creates SSLSession implementation
- *
- * @param cipher_suite
- * @param sr
- */
- public SSLSessionImpl(CipherSuite cipher_suite, SecureRandom sr) {
- creationTime = System.currentTimeMillis();
- lastAccessedTime = creationTime;
- if (cipher_suite == null) {
- this.cipherSuite = CipherSuite.TLS_NULL_WITH_NULL_NULL;
- id = new byte[0];
- isServer = false;
- isValid = false;
- } else {
- this.cipherSuite = cipher_suite;
- id = new byte[32];
- sr.nextBytes(id);
- long time = creationTime / 1000;
- id[28] = (byte) ((time & 0xFF000000) >>> 24);
- id[29] = (byte) ((time & 0x00FF0000) >>> 16);
- id[30] = (byte) ((time & 0x0000FF00) >>> 8);
- id[31] = (byte) ((time & 0x000000FF));
- isServer = true;
- }
-
- }
-
- /**
- * Creates SSLSession implementation
- *
- * @param sr
- */
- public SSLSessionImpl(SecureRandom sr) {
- this(null, sr);
- }
-
- public int getApplicationBufferSize() {
- return SSLRecordProtocol.MAX_DATA_LENGTH;
- }
-
- public String getCipherSuite() {
- return cipherSuite.getName();
- }
-
- public long getCreationTime() {
- return creationTime;
- }
-
- public byte[] getId() {
- return id;
- }
-
- public long getLastAccessedTime() {
- return lastAccessedTime;
- }
-
- public Certificate[] getLocalCertificates() {
- return localCertificates;
- }
-
- public Principal getLocalPrincipal() {
- if (localCertificates != null && localCertificates.length > 0) {
- return localCertificates[0].getSubjectX500Principal();
- }
- return null;
- }
-
- public int getPacketBufferSize() {
- return SSLRecordProtocol.MAX_SSL_PACKET_SIZE;
- }
-
- public javax.security.cert.X509Certificate[] getPeerCertificateChain()
- throws SSLPeerUnverifiedException {
- if (peerCertificates == null) {
- throw new SSLPeerUnverifiedException("No peer certificate");
- }
- javax.security.cert.X509Certificate[] certs = new javax.security.cert.X509Certificate[peerCertificates.length];
- for (int i = 0; i < certs.length; i++) {
- try {
- certs[i] = javax.security.cert.X509Certificate.getInstance(peerCertificates[i]
- .getEncoded());
- } catch (javax.security.cert.CertificateException e) {
- } catch (CertificateEncodingException e) {
- }
- }
- return certs;
- }
-
- public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException {
- if (peerCertificates == null) {
- throw new SSLPeerUnverifiedException("No peer certificate");
- }
- return peerCertificates;
- }
-
- public String getPeerHost() {
- return peerHost;
- }
-
- public int getPeerPort() {
- return peerPort;
- }
-
- public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
- if (peerCertificates == null) {
- throw new SSLPeerUnverifiedException("No peer certificate");
- }
- return peerCertificates[0].getSubjectX500Principal();
- }
-
- public String getProtocol() {
- return (protocol == null) ? "NONE" : protocol.name;
- }
-
- public SSLSessionContext getSessionContext() {
- SecurityManager sm = System.getSecurityManager();
- if (sm != null) {
- sm.checkPermission(new SSLPermission("getSSLSessionContext"));
- }
- return context;
- }
-
- public Object getValue(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- return values.get(new ValueKey(name));
- }
-
- public String[] getValueNames() {
- final Vector<String> v = new Vector<String>();
- final AccessControlContext currAcc = AccessController.getContext();
- for (ValueKey key : values.keySet()) {
- if ((currAcc == null && key.acc == null)
- || (currAcc != null && currAcc.equals(key.acc))) {
- v.add(key.name);
- }
- }
- return v.toArray(new String[v.size()]);
- }
-
- public void invalidate() {
- isValid = false;
- context = null;
- }
-
- public boolean isValid() {
- if (isValid && context != null && context.getSessionTimeout() != 0
- && lastAccessedTime + context.getSessionTimeout() > System.currentTimeMillis()) {
- isValid = false;
- }
- return isValid;
- }
-
- public void putValue(String name, Object value) {
- if (name == null || value == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- Object old = values.put(new ValueKey(name), value);
- if (value instanceof SSLSessionBindingListener) {
- ((SSLSessionBindingListener) value).valueBound(new SSLSessionBindingEvent(this, name));
- }
- if (old instanceof SSLSessionBindingListener) {
- ((SSLSessionBindingListener) old).valueUnbound(new SSLSessionBindingEvent(this, name));
- }
-
- }
-
- public void removeValue(String name) {
- if (name == null) {
- throw new IllegalArgumentException("Parameter is null");
- }
- Object old = values.remove(new ValueKey(name));
- if (old instanceof SSLSessionBindingListener) {
- SSLSessionBindingListener listener = (SSLSessionBindingListener) old;
- listener.valueUnbound(new SSLSessionBindingEvent(this, name));
- }
- }
-
- @Override
- public Object clone() {
- try {
- return super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError(e);
- }
- }
-
- /**
- * Sets the address of the peer
- *
- * @param peerHost
- * @param peerPort
- */
- void setPeer(String peerHost, int peerPort) {
- this.peerHost = peerHost;
- this.peerPort = peerPort;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLStreamedInput.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLStreamedInput.java
deleted file mode 100644
index c040653..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLStreamedInput.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * This class acts like a filtered input stream: it takes
- * the bytes from another InputStream.
- */
-public class SSLStreamedInput extends SSLInputStream {
-
- private InputStream in;
-
- public SSLStreamedInput(InputStream in) {
- this.in = in;
- }
-
- @Override
- public int available() throws IOException {
- return in.available();
- }
-
- /**
- * Read an opaque value from the stream.
- * @return the value read from the underlying stream.
- * @throws IOException if the data could not be read from
- * the underlying stream
- * @throws org.apache.harmony.xnet.provider.jsse.EndOfSourceException if the end of the underlying
- * stream has been reached.
- */
- @Override
- public int read() throws IOException {
- int res = in.read();
- if (res < 0) {
- throw new EndOfSourceException();
- }
- return res;
- }
-}
-
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLv3Constants.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLv3Constants.java
deleted file mode 100644
index 07aaca8..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/SSLv3Constants.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-/**
- *
- * Contains SSL 3.0 constants
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec.</a>
- */
-public class SSLv3Constants {
-
- /**
- * Client is a sender. Used in hash calculating for finished message.
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.6.9
- * Finished</a>
- */
- static final byte[] client = new byte[] { 0x43, 0x4C, 0x4E, 0x54 };
-
- /**
- * Server is a sender. Used in hash calculating for finished message.
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.6.9
- * Finished</a>
- */
- static final byte[] server = new byte[] { 0x53, 0x52, 0x56, 0x52 };
-
- /**
- * pad_1 for MD5
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.2.3.1
- * Null or standard stream cipher</a>
- */
- static final byte[] MD5pad1 = new byte[] { 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36 };
-
- /**
- * pad_1 for SHA
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.2.3.1
- * Null or standard stream cipher</a>
- */
- static final byte[] SHApad1 = new byte[] { 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
- 0x36, 0x36, 0x36 };
-
- /**
- * pad_2 for MD5
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.2.3.1
- * Null or standard stream cipher</a>
- */
- static final byte[] MD5pad2 = new byte[] { 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C };
-
- /**
- * pad_2 for SHA
- * @see <a href="http://wp.netscape.com/eng/ssl3">SSL 3.0 Spec., 5.2.3.1
- * Null or standard stream cipher</a>
- */
- static final byte[] SHApad2 = new byte[] { 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C, 0x5C,
- 0x5C, 0x5C, 0x5C };
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java
deleted file mode 100644
index b76c42f..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHandshakeImpl.java
+++ /dev/null
@@ -1,724 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.SSLv3Constants;
-import org.apache.harmony.xnet.provider.jsse.SSLSessionImpl;
-import org.apache.harmony.xnet.provider.jsse.ProtocolVersion;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.AccessController;
-import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.PrivilegedExceptionAction;
-import java.security.PublicKey;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.security.interfaces.RSAPublicKey;
-
-import java.util.Arrays;
-
-import javax.crypto.Cipher;
-import javax.crypto.KeyAgreement;
-import javax.crypto.interfaces.DHPublicKey;
-import javax.crypto.spec.DHParameterSpec;
-import javax.crypto.spec.DHPublicKeySpec;
-import javax.net.ssl.X509ExtendedKeyManager;
-import javax.net.ssl.X509KeyManager;
-import javax.net.ssl.X509TrustManager;
-
-/**
- * Server side handshake protocol implementation.
- * Handshake protocol operates on top of the Record Protocol.
- * It responsible for negotiating a session.
- *
- * The implementation processes inbound client handshake messages,
- * creates and sends respond messages. Outbound messages are supplied
- * to Record Protocol. Detected errors are reported to the Alert protocol.
- *
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.
- * Handshake protocol.</a>
- *
- */
-public class ServerHandshakeImpl extends HandshakeProtocol {
-
- // private key used in key exchange
- private PrivateKey privKey;
-
- /**
- * Creates Server Handshake Implementation
- *
- * @param owner
- */
- public ServerHandshakeImpl(Object owner) {
- super(owner);
- status = NEED_UNWRAP;
- }
-
- /**
- * Start session negotiation
- */
- @Override
- public void start() {
- if (session == null) { // initial handshake
- status = NEED_UNWRAP;
- return; // wait client hello
- }
- if (clientHello != null && this.status != FINISHED) {
- // current negotiation has not completed
- return; // ignore
- }
-
- // renegotiation
- sendHelloRequest();
- status = NEED_UNWRAP;
- }
-
- /**
- * Proceses inbound handshake messages
- * @param bytes
- */
- @Override
- public void unwrap(byte[] bytes) {
-
- io_stream.append(bytes);
- while (io_stream.available() > 0) {
- int handshakeType;
- int length;
- io_stream.mark();
- try {
- handshakeType = io_stream.read();
- length = io_stream.readUint24();
- if (io_stream.available() < length) {
- io_stream.reset();
- return;
- }
-
- switch (handshakeType) {
- case 1: // CLIENT_HELLO
- if (clientHello != null && this.status != FINISHED) {
- // Client hello has been received during handshake
- unexpectedMessage();
- return;
- }
- // if protocol planed to send Hello Request message
- // - cancel this demand.
- needSendHelloRequest = false;
- clientHello = new ClientHello(io_stream, length);
- if (nonBlocking) {
- delegatedTasks.add(new DelegatedTask(new PrivilegedExceptionAction<Void>() {
- public Void run() throws Exception {
- processClientHello();
- return null;
- }
- }, this, AccessController.getContext()));
- return;
- }
- processClientHello();
- break;
-
- case 11: // CLIENT CERTIFICATE
- if (isResuming || certificateRequest == null
- || serverHelloDone == null || clientCert != null) {
- unexpectedMessage();
- return;
- }
- clientCert = new CertificateMessage(io_stream, length);
- if (clientCert.certs.length == 0) {
- if (parameters.getNeedClientAuth()) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "HANDSHAKE FAILURE: no client certificate received");
- }
- } else {
- String authType = clientCert.certs[0].getPublicKey()
- .getAlgorithm();
- try {
- parameters.getTrustManager().checkClientTrusted(
- clientCert.certs, authType);
- } catch (CertificateException e) {
- fatalAlert(AlertProtocol.BAD_CERTIFICATE,
- "Untrusted Client Certificate ", e);
- }
- session.peerCertificates = clientCert.certs;
- }
- break;
-
- case 15: // CERTIFICATE_VERIFY
- if (isResuming
- || clientKeyExchange == null
- || clientCert == null
- || clientKeyExchange.isEmpty() //client certificate
- // contains fixed DH
- // parameters
- || certificateVerify != null
- || changeCipherSpecReceived) {
- unexpectedMessage();
- return;
- }
- certificateVerify = new CertificateVerify(io_stream, length);
-
- DigitalSignature ds = new DigitalSignature(session.cipherSuite.keyExchange);
- ds.init(serverCert.certs[0]);
- byte[] md5_hash = null;
- byte[] sha_hash = null;
-
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT) {
- md5_hash = io_stream.getDigestMD5withoutLast();
- sha_hash = io_stream.getDigestSHAwithoutLast();
- } else if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT) {
- sha_hash = io_stream.getDigestSHAwithoutLast();
- } else if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_DH_anon_EXPORT) {
- }
- ds.setMD5(md5_hash);
- ds.setSHA(sha_hash);
- if (!ds.verifySignature(certificateVerify.signedHash)) {
- fatalAlert(AlertProtocol.DECRYPT_ERROR,
- "DECRYPT ERROR: CERTIFICATE_VERIFY incorrect signature");
- }
- break;
- case 16: // CLIENT_KEY_EXCHANGE
- if (isResuming
- || serverHelloDone == null
- || clientKeyExchange != null
- || (clientCert == null && parameters
- .getNeedClientAuth())) {
- unexpectedMessage();
- return;
- }
- if (session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA
- || session.cipherSuite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- clientKeyExchange = new ClientKeyExchange(io_stream,
- length, serverHello.server_version[1] == 1,
- true);
- Cipher c = null;
- try {
- c = Cipher.getInstance("RSA/ECB/PKCS1Padding");
- c.init(Cipher.DECRYPT_MODE, privKey);
- preMasterSecret = c
- .doFinal(clientKeyExchange.exchange_keys);
- // check preMasterSecret:
- if (preMasterSecret.length != 48
- || preMasterSecret[0] != clientHello.client_version[0]
- || preMasterSecret[1] != clientHello.client_version[1]) {
- // incorrect preMasterSecret
- // prevent an attack (see TLS 1.0 spec., 7.4.7.1.)
- preMasterSecret = new byte[48];
- parameters.getSecureRandom().nextBytes(
- preMasterSecret);
- }
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "INTERNAL ERROR", e);
- }
- } else { // diffie hellman key exchange
- clientKeyExchange = new ClientKeyExchange(io_stream,
- length, serverHello.server_version[1] == 1,
- false);
- if (clientKeyExchange.isEmpty()) {
- // TODO check that client cert. DH params
- // matched server cert. DH params
-
- // client cert. contains fixed DH parameters
- preMasterSecret = ((DHPublicKey) clientCert.certs[0]
- .getPublicKey()).getY().toByteArray();
- } else {
- PublicKey clientPublic;
- KeyAgreement agreement;
- try {
- KeyFactory kf = null;
- try {
- kf = KeyFactory.getInstance("DH");
- } catch (NoSuchAlgorithmException ee) {
- kf = KeyFactory
- .getInstance("DiffieHellman");
- }
- try {
- agreement = KeyAgreement.getInstance("DH");
- } catch (NoSuchAlgorithmException ee) {
- agreement = KeyAgreement
- .getInstance("DiffieHellman");
- }
- clientPublic = kf
- .generatePublic(new DHPublicKeySpec(
- new BigInteger(
- 1,
- clientKeyExchange.exchange_keys),
- serverKeyExchange.par1,
- serverKeyExchange.par2));
- agreement.init(privKey);
- agreement.doPhase(clientPublic, true);
- preMasterSecret = agreement.generateSecret();
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR,
- "INTERNAL ERROR", e);
- return;
- }
- }
- }
-
- computerMasterSecret();
- break;
-
- case 20: // FINISHED
- if (!isResuming && !changeCipherSpecReceived) {
- unexpectedMessage();
- return;
- }
-
- clientFinished = new Finished(io_stream, length);
- verifyFinished(clientFinished.getData());
- // BEGIN android-added
- session.context = parameters.getServerSessionContext();
- // END android-added
- parameters.getServerSessionContext().putSession(session);
- if (!isResuming) {
- sendChangeCipherSpec();
- } else {
- session.lastAccessedTime = System.currentTimeMillis();
- status = FINISHED;
- }
- break;
- default:
- unexpectedMessage();
- return;
- }
- } catch (IOException e) {
- // io stream dosn't contain complete handshake message
- io_stream.reset();
- return;
- }
- }
- }
- /**
- * Processes SSLv2 Hello message
- * @ see TLS 1.0 spec., E.1. Version 2 client hello
- * @param bytes
- */
- @Override
- public void unwrapSSLv2(byte[] bytes) {
- io_stream.append(bytes);
- io_stream.mark();
- try {
- clientHello = new ClientHello(io_stream);
- } catch (IOException e) {
- io_stream.reset();
- return;
- }
- if (nonBlocking) {
- delegatedTasks.add(new DelegatedTask(
- new PrivilegedExceptionAction<Void>() {
- public Void run() throws Exception {
- processClientHello();
- return null;
- }
- }, this, AccessController.getContext()));
- return;
- }
- processClientHello();
- }
-
- /**
- *
- * Processes Client Hello message.
- * Server responds to client hello message with server hello
- * and (if necessary) server certificate, server key exchange,
- * certificate request, and server hello done messages.
- */
- void processClientHello() {
- CipherSuite cipher_suite;
-
- // check that clientHello contains CompressionMethod.null
- checkCompression: {
- for (int i = 0; i < clientHello.compression_methods.length; i++) {
- if (clientHello.compression_methods[i] == 0) {
- break checkCompression;
- }
- }
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "HANDSHAKE FAILURE. Incorrect client hello message");
- }
-
- if (!ProtocolVersion.isSupported(clientHello.client_version)) {
- fatalAlert(AlertProtocol.PROTOCOL_VERSION,
- "PROTOCOL VERSION. Unsupported client version "
- + clientHello.client_version[0]
- + clientHello.client_version[1]);
- }
-
- isResuming = false;
- FIND: if (clientHello.session_id.length != 0) {
- // client wishes to reuse session
-
- SSLSessionImpl sessionToResume;
- boolean reuseCurrent = false;
-
- // reuse current session
- if (session != null
- && Arrays.equals(session.id, clientHello.session_id)) {
- if (session.isValid()) {
- isResuming = true;
- break FIND;
- }
- reuseCurrent = true;
- }
-
- // find session in cash
- sessionToResume = findSessionToResume(clientHello.session_id);
- if (sessionToResume == null || !sessionToResume.isValid()) {
- if (!parameters.getEnableSessionCreation()) {
- if (reuseCurrent) {
- // we can continue current session
- sendWarningAlert(AlertProtocol.NO_RENEGOTIATION);
- status = NOT_HANDSHAKING;
- clearMessages();
- return;
- }
- // throw AlertException
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "SSL Session may not be created");
- }
- session = null;
- } else {
- session = (SSLSessionImpl)sessionToResume.clone();
- isResuming = true;
- }
- }
-
- if (isResuming) {
- cipher_suite = session.cipherSuite;
- // clientHello.cipher_suites must include at least cipher_suite from the session
- checkCipherSuite: {
- for (int i = 0; i < clientHello.cipher_suites.length; i++) {
- if (cipher_suite.equals(clientHello.cipher_suites[i])) {
- break checkCipherSuite;
- }
- }
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "HANDSHAKE FAILURE. Incorrect client hello message");
- }
- } else {
- cipher_suite = selectSuite(clientHello.cipher_suites);
- if (cipher_suite == null) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "HANDSHAKE FAILURE. NO COMMON SUITE");
- }
- if (!parameters.getEnableSessionCreation()) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE,
- "SSL Session may not be created");
- }
- session = new SSLSessionImpl(cipher_suite, parameters.getSecureRandom());
- session.setPeer(engineOwner.getPeerHost(), engineOwner.getPeerPort());
- }
-
- recordProtocol.setVersion(clientHello.client_version);
- session.protocol = ProtocolVersion.getByVersion(clientHello.client_version);
- session.clientRandom = clientHello.random;
-
- // create server hello message
- serverHello = new ServerHello(parameters.getSecureRandom(),
- clientHello.client_version,
- session.getId(), cipher_suite, (byte) 0); //CompressionMethod.null
- session.serverRandom = serverHello.random;
- send(serverHello);
- if (isResuming) {
- sendChangeCipherSpec();
- return;
- }
-
- // create and send server certificate message if needed
- if (!cipher_suite.isAnonymous()) { // need to send server certificate
- X509Certificate[] certs = null;
- String certType = null;
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT) {
- certType = "RSA";
- } else if (cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_DSS
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT) {
- certType = "DSA";
- } else if (cipher_suite.keyExchange == CipherSuite.KeyExchange_DH_DSS) {
- certType = "DH_DSA";
- } else if (cipher_suite.keyExchange == CipherSuite.KeyExchange_DH_RSA) {
- certType = "DH_RSA";
- }
- // obtain certificates from key manager
- String alias = null;
- X509KeyManager km = parameters.getKeyManager();
- if (km instanceof X509ExtendedKeyManager) {
- X509ExtendedKeyManager ekm = (X509ExtendedKeyManager)km;
- // BEGIN android-removed
- // if (this.socketOwner != null) {
- // alias = ekm.chooseServerAlias(certType, null,
- // this.socketOwner);
- // } else {
- // END android-removed
- alias = ekm.chooseEngineServerAlias(certType, null,
- this.engineOwner);
- // BEGIN android-removed
- // }
- // END android-removed
- if (alias != null) {
- certs = ekm.getCertificateChain(alias);
- }
- } else {
- // BEGIN android-removed
- // alias = km.chooseServerAlias(certType, null, this.socketOwner);
- // if (alias != null) {
- // END android-removed
- certs = km.getCertificateChain(alias);
- // BEGIN android-removed
- // }
- // END android-removed
- }
-
- if (certs == null) {
- fatalAlert(AlertProtocol.HANDSHAKE_FAILURE, "NO SERVER CERTIFICATE FOUND");
- return;
- }
- session.localCertificates = certs;
- serverCert = new CertificateMessage(certs);
- privKey = parameters.getKeyManager().getPrivateKey(alias);
- send(serverCert);
- }
-
- // create and send server key exchange message if needed
- RSAPublicKey rsakey = null;
- DHPublicKeySpec dhkeySpec = null;
- byte[] hash = null;
- BigInteger p = null;
- BigInteger g = null;
-
- KeyPairGenerator kpg = null;
-
- try {
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- PublicKey pk = serverCert.certs[0].getPublicKey();
- if (getRSAKeyLength(pk) > 512) {
- // key is longer than 512 bits
- kpg = KeyPairGenerator.getInstance("RSA");
- kpg.initialize(512);
- }
- } else if (cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_DSS
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_DSS_EXPORT
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_RSA
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DHE_RSA_EXPORT
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DH_anon
- || cipher_suite.keyExchange == CipherSuite.KeyExchange_DH_anon_EXPORT) {
- try {
- kpg = KeyPairGenerator.getInstance("DH");
- } catch (NoSuchAlgorithmException ee) {
- kpg = KeyPairGenerator.getInstance("DiffieHellman");
- }
- p = new BigInteger(1, DHParameters.getPrime());
- g = new BigInteger("2");
- DHParameterSpec spec = new DHParameterSpec(p, g);
- kpg.initialize(spec);
- }
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
- }
-
- if (kpg != null) {
- // need to send server key exchange message
- DigitalSignature ds = new DigitalSignature(cipher_suite.keyExchange);
- KeyPair kp = null;
- try {
- kp = kpg.genKeyPair();
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- rsakey = (RSAPublicKey) kp.getPublic();
- } else {
- DHPublicKey dhkey = (DHPublicKey) kp.getPublic();
- KeyFactory kf = null;
- try {
- kf = KeyFactory.getInstance("DH");
- } catch (NoSuchAlgorithmException e) {
- kf = KeyFactory.getInstance("DiffieHellman");
- }
- dhkeySpec = kf.getKeySpec(dhkey,
- DHPublicKeySpec.class);
- }
- if (!cipher_suite.isAnonymous()) { // calculate signed_params
-
- // init by private key which correspond to
- // server certificate
- ds.init(privKey);
-
- // use emphemeral key for key exchange
- privKey = kp.getPrivate();
- ds.update(clientHello.getRandom());
- ds.update(serverHello.getRandom());
-
- byte[] tmp;
- byte[] tmpLength = new byte[2];
-//FIXME 1_byte==0x00
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getModulus());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- tmp = ServerKeyExchange.toUnsignedByteArray(rsakey.getPublicExponent());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- } else {
- tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getP());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getG());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- tmp = ServerKeyExchange.toUnsignedByteArray(dhkeySpec.getY());
- tmpLength[0] = (byte) ((tmp.length & 0xFF00) >>> 8);
- tmpLength[1] = (byte) (tmp.length & 0xFF);
- ds.update(tmpLength);
- ds.update(tmp);
- }
- hash = ds.sign();
- } else {
- privKey = kp.getPrivate(); // use emphemeral key for key exchange
- }
- } catch (Exception e) {
- fatalAlert(AlertProtocol.INTERNAL_ERROR, "INTERNAL ERROR", e);
- }
-
- if (cipher_suite.keyExchange == CipherSuite.KeyExchange_RSA_EXPORT) {
- serverKeyExchange = new ServerKeyExchange(rsakey.getModulus(),
- rsakey.getPublicExponent(), null, hash);
- } else {
- serverKeyExchange = new ServerKeyExchange(p,
- g, dhkeySpec.getY(), hash);
- }
- send(serverKeyExchange);
- }
-
- // CERTIFICATE_REQUEST
- certRequest: if (parameters.getWantClientAuth()
- || parameters.getNeedClientAuth()) {
- X509Certificate[] accepted;
- try {
- X509TrustManager tm = parameters.getTrustManager();
- accepted = tm.getAcceptedIssuers();
- } catch (ClassCastException e) {
- // don't send certificateRequest
- break certRequest;
- }
- byte[] requestedClientCertTypes = {1, 2}; // rsa sign, dsa sign
- certificateRequest = new CertificateRequest(
- requestedClientCertTypes, accepted);
- send(certificateRequest);
- }
-
- // SERVER_HELLO_DONE
- serverHelloDone = new ServerHelloDone();
- send(serverHelloDone);
- status = NEED_UNWRAP;
- }
-
- /**
- * Creates and sends finished message
- */
- @Override
- protected void makeFinished() {
- byte[] verify_data;
- boolean isTLS = (serverHello.server_version[1] == 1); // TLS 1.0 protocol
- if (isTLS) {
- verify_data = new byte[12];
- computerVerifyDataTLS("server finished", verify_data);
- } else { // SSL 3.0 protocol (http://wp.netscape.com/eng/ssl3)
- verify_data = new byte[36];
- computerVerifyDataSSLv3(SSLv3Constants.server, verify_data);
- }
- serverFinished = new Finished(verify_data);
- send(serverFinished);
- if (isResuming) {
- if (isTLS) {
- computerReferenceVerifyDataTLS("client finished");
- } else {
- computerReferenceVerifyDataSSLv3(SSLv3Constants.client);
- }
- status = NEED_UNWRAP;
- } else {
- session.lastAccessedTime = System.currentTimeMillis();
- status = FINISHED;
- }
- }
-
- // find sesssion in the session hash
- private SSLSessionImpl findSessionToResume(byte[] session_id) {
- return (SSLSessionImpl)parameters.getServerSessionContext().getSession(session_id);
- }
-
- // find appropriate cipher_suite in the client suites
- private CipherSuite selectSuite(CipherSuite[] client_suites) {
- for (int i = 0; i < client_suites.length; i++) {
- if (!client_suites[i].supported) {
- continue;
- }
- // BEGIN android-changed
- for (int j = 0; j < parameters.getEnabledCipherSuitesMember().length; j++) {
- if (client_suites[i].equals(parameters.getEnabledCipherSuitesMember()[j])) {
- return client_suites[i];
- }
- }
- // END android-changed
- }
- return null;
- }
-
- /**
- * Processes inbound ChangeCipherSpec message
- */
- @Override
- public void receiveChangeCipherSpec() {
- if (isResuming) {
- if (serverFinished == null) {
- unexpectedMessage();
- } else {
- changeCipherSpecReceived = true;
- }
- } else {
- if ((parameters.getNeedClientAuth() && clientCert == null)
- || clientKeyExchange == null
- || (clientCert != null && !clientKeyExchange.isEmpty() && certificateVerify == null)) {
- unexpectedMessage();
- } else {
- changeCipherSpecReceived = true;
- }
- if (serverHello.server_version[1] == 1) {
- computerReferenceVerifyDataTLS("client finished");
- } else {
- computerReferenceVerifyDataSSLv3(SSLv3Constants.client);
- }
- }
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHello.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHello.java
deleted file mode 100644
index 1cd9624..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHello.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-
-import java.io.IOException;
-import java.security.SecureRandom;
-
-/**
- *
- * Represents server hello message.
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.1.3.
- * Server hello.</a>
- */
-public class ServerHello extends Message {
-
- /**
- * Server version
- */
- byte[] server_version = new byte[2];
-
- /**
- * Random bytes
- */
- byte[] random = new byte[32];
-
- /**
- * Session id
- */
- byte[] session_id;
-
- /**
- * Selected cipher suite
- */
- CipherSuite cipher_suite;
-
- /**
- * Selected compression method
- */
- byte compression_method;
-
- /**
- * Creates outbound message
- * @param sr
- * @param server_version
- * @param session_id
- * @param cipher_suite
- * @param compression_method
- */
- public ServerHello(SecureRandom sr, byte[] server_version,
- byte[] session_id, CipherSuite cipher_suite, byte compression_method) {
- long gmt_unix_time = new java.util.Date().getTime() / 1000;
- sr.nextBytes(random);
- random[0] = (byte) ((gmt_unix_time & 0xFF000000) >>> 24);
- random[1] = (byte) ((gmt_unix_time & 0xFF0000) >>> 16);
- random[2] = (byte) ((gmt_unix_time & 0xFF00) >>> 8);
- random[3] = (byte) (gmt_unix_time & 0xFF);
- this.session_id = session_id;
- this.cipher_suite = cipher_suite;
- this.compression_method = compression_method;
- this.server_version = server_version;
- length = 38 + session_id.length;
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public ServerHello(HandshakeIODataStream in, int length) throws IOException {
-
- server_version[0] = (byte) in.read();
- server_version[1] = (byte) in.read();
- in.read(random, 0, 32);
- int size = in.readUint8();
- session_id = new byte[size];
- in.read(session_id, 0, size);
- byte b0 = (byte) in.read();
- byte b1 = (byte) in.read();
- cipher_suite = CipherSuite.getByCode(b0, b1);
- compression_method = (byte) in.read();
- this.length = 38 + session_id.length;
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect ServerHello");
- }
-
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- out.write(server_version);
- out.write(random);
- out.writeUint8(session_id.length);
- out.write(session_id);
- out.write(cipher_suite.toBytes());
- out.write(compression_method);
- length = 38 + session_id.length;
- }
-
- /**
- * Returns server random
- * @return
- */
- public byte[] getRandom() {
- return random;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.SERVER_HELLO;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHelloDone.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHelloDone.java
deleted file mode 100644
index 73b6a81..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerHelloDone.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-
-import java.io.IOException;
-
-/**
- *
- * Represents server hello done message
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.5.
- * Server hello done</a>
- *
- */
-public class ServerHelloDone extends Message {
-
- /**
- * Creates outbound message
- *
- */
- public ServerHelloDone() {
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @throws IOException
- */
- public ServerHelloDone(HandshakeIODataStream in, int length)
- throws IOException {
- if (length != 0) {
- fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect ServerHelloDone");
- }
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- }
-
- /**
- * Returns message length
- * @return
- */
- @Override
- public int length() {
- return 0;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.SERVER_HELLO_DONE;
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerKeyExchange.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerKeyExchange.java
deleted file mode 100644
index af056a3..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerKeyExchange.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.apache.harmony.xnet.provider.jsse.Message;
-
-import java.io.IOException;
-import java.math.BigInteger;
-import java.security.KeyFactory;
-import java.security.interfaces.RSAPublicKey;
-import java.security.spec.RSAPublicKeySpec;
-
-/**
- *
- * Represents server key exchange message.
- * @see <a href="http://www.ietf.org/rfc/rfc2246.txt">TLS 1.0 spec., 7.4.3.
- * Server key exchange message.</a>
- *
- */
-public class ServerKeyExchange extends Message {
-
- // ServerRSAParams ServerDHParams
- final BigInteger par1; // rsa_modulus dh_p
- final byte[] bytes1;
-
- final BigInteger par2; // rsa_exponent dh_g
- final byte[] bytes2;
-
- final BigInteger par3; // dh_Ys
- final byte[] bytes3;
-
- /**
- * Signature
- */
- final byte[] hash;
-
- private RSAPublicKey key;
-
- /**
- * Creates outbound message
- * @param par1 rsa_modulus or dh_p
- * @param par2 rsa_exponent or dh_g
- * @param par3 dh_Ys for ServerDHParams; should be null for ServerRSAParams
- * @param hash should be null for anonymous SignatureAlgorithm
- */
- public ServerKeyExchange(BigInteger par1, BigInteger par2, BigInteger par3,
- byte[] hash) {
- this.par1 = par1;
- this.par2 = par2;
- this.par3 = par3;
- this.hash = hash;
-
- bytes1 = toUnsignedByteArray(this.par1);
-
- bytes2 = toUnsignedByteArray(this.par2);
-
- length = 4 + bytes1.length + bytes2.length;
- if (hash != null) {
- length += 2 + hash.length;
- }
- if (par3 == null) {
- bytes3 = null;
- return;
- }
- bytes3 = toUnsignedByteArray(this.par3);
- length += 2 + bytes3.length;
- }
-
- /**
- * Remove first byte if 0. Needed because BigInteger.toByteArray() sometimes
- * returns a zero prefix.
- */
- public static byte[] toUnsignedByteArray(BigInteger bi) {
- if (bi == null) {
- return null;
- }
- byte[] bb = bi.toByteArray();
- // bb is not null, and has at least 1 byte - ZERO is represented as [0]
- if (bb[0] == 0) {
- byte[] noZero = new byte[bb.length - 1];
- System.arraycopy(bb, 1, noZero, 0, noZero.length);
- return noZero;
- } else {
- return bb;
- }
- }
-
- /**
- * Creates inbound message
- * @param in
- * @param length
- * @param keyExchange
- * @throws IOException
- */
- public ServerKeyExchange(HandshakeIODataStream in, int length,
- int keyExchange) throws IOException {
-
- int size = in.readUint16();
- bytes1 = in.read(size);
- par1 = new BigInteger(1, bytes1);
- this.length = 2 + bytes1.length;
- size = in.readUint16();
- bytes2 = in.read(size);
- par2 = new BigInteger(1, bytes2);
- this.length += 2 + bytes2.length;
- if (keyExchange != CipherSuite.KeyExchange_RSA_EXPORT) {
- size = in.readUint16();
- bytes3 = in.read(size);
- par3 = new BigInteger(1, bytes3);
- this.length += 2 + bytes3.length;
- } else {
- par3 = null;
- bytes3 = null;
- }
- if (keyExchange != CipherSuite.KeyExchange_DH_anon_EXPORT
- && keyExchange != CipherSuite.KeyExchange_DH_anon) {
- size = in.readUint16();
- hash = in.read(size);
- this.length += 2 + hash.length;
- } else {
- hash = null;
- }
- if (this.length != length) {
- fatalAlert(AlertProtocol.DECODE_ERROR,
- "DECODE ERROR: incorrect ServerKeyExchange");
- }
- }
-
- /**
- * Sends message
- * @param out
- */
- @Override
- public void send(HandshakeIODataStream out) {
- out.writeUint16(bytes1.length);
- out.write(bytes1);
- out.writeUint16(bytes2.length);
- out.write(bytes2);
- if (bytes3 != null) {
- out.writeUint16(bytes3.length);
- out.write(bytes3);
- }
- if (hash != null) {
- out.writeUint16(hash.length);
- out.write(hash);
- }
- }
-
- /**
- * Returns RSAPublicKey generated using ServerRSAParams
- * (rsa_modulus and rsa_exponent).
- *
- * @return
- */
- public RSAPublicKey getRSAPublicKey() {
- if (key != null) {
- return key;
- }
- try {
- KeyFactory kf = KeyFactory.getInstance("RSA");
- key = (RSAPublicKey) kf.generatePublic(new RSAPublicKeySpec(par1,
- par2));
- } catch (Exception e) {
- return null;
- }
- return key;
- }
-
- /**
- * Returns message type
- * @return
- */
- @Override
- public int getType() {
- return Handshake.SERVER_KEY_EXCHANGE;
- }
-
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.java
deleted file mode 100644
index 160188d..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/ServerSessionContext.java
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Iterator;
-import java.util.ArrayList;
-import java.util.Arrays;
-
-import javax.net.ssl.SSLSession;
-
-/**
- * Caches server sessions. Indexes by session ID. Users typically look up
- * sessions using the ID provided by an SSL client.
- */
-public class ServerSessionContext extends AbstractSessionContext {
-
- /*
- * TODO: Expire timed-out sessions more pro-actively.
- */
-
- private final Map<ByteArray, SSLSession> sessions
- = new LinkedHashMap<ByteArray, SSLSession>() {
- @Override
- protected boolean removeEldestEntry(
- Map.Entry<ByteArray, SSLSession> eldest) {
- return maximumSize > 0 && size() > maximumSize;
- }
- };
-
- private final SSLServerSessionCache persistentCache;
-
- public ServerSessionContext(int sslCtxNativePointer,
- SSLServerSessionCache persistentCache) {
- super(sslCtxNativePointer, 100, 0);
- this.persistentCache = persistentCache;
-
- // TODO make sure SSL_CTX does not automaticaly clear sessions we want it to cache
- // SSL_CTX_set_session_cache_mode(sslCtxNativePointer, SSL_SESS_CACHE_NO_AUTO_CLEAR);
-
- // TODO remove SSL_CTX session cache limit so we can manage it
- // SSL_CTX_sess_set_cache_size(sslCtxNativePointer, 0);
-
- // TODO override trimToSize to use SSL_CTX_sessions to remove from native cache
- }
-
- Iterator<SSLSession> sessionIterator() {
- synchronized (sessions) {
- SSLSession[] array = sessions.values().toArray(
- new SSLSession[sessions.size()]);
- return Arrays.asList(array).iterator();
- }
- }
-
- void trimToSize() {
- synchronized (sessions) {
- int size = sessions.size();
- if (size > maximumSize) {
- int removals = size - maximumSize;
- Iterator<SSLSession> i = sessions.values().iterator();
- do {
- i.next();
- i.remove();
- } while (--removals > 0);
- }
- }
- }
-
- public void setSessionTimeout(int seconds)
- throws IllegalArgumentException {
- if (seconds < 0) {
- throw new IllegalArgumentException("seconds < 0");
- }
- timeout = seconds;
- }
-
- public SSLSession getSession(byte[] sessionId) {
- ByteArray key = new ByteArray(sessionId);
- synchronized (sessions) {
- SSLSession session = sessions.get(key);
- if (session != null) {
- return session;
- }
- }
-
- // Check persistent cache.
- if (persistentCache != null) {
- byte[] data = persistentCache.getSessionData(sessionId);
- if (data != null) {
- SSLSession session = toSession(data, null, -1);
- if (session != null) {
- synchronized (sessions) {
- sessions.put(key, session);
- }
- return session;
- }
- }
- }
-
- return null;
- }
-
- @Override
- void putSession(SSLSession session) {
- byte[] id = session.getId();
- if (id.length == 0) {
- return;
- }
- ByteArray key = new ByteArray(id);
- synchronized (sessions) {
- sessions.put(key, session);
- }
-
- // TODO: In background thread.
- if (persistentCache != null) {
- byte[] data = toBytes(session);
- if (data != null) {
- persistentCache.putSessionData(session, data);
- }
- }
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java
deleted file mode 100644
index c473864..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerFactoryImpl.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.security.AccessController;
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
-
-import javax.net.ssl.ManagerFactoryParameters;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.TrustManagerFactorySpi;
-
-/**
- *
- * TrustManagerFactory service provider interface implementation.
- *
- * @see javax.net.ssl.TrustManagerFactorySpi
- */
-public class TrustManagerFactoryImpl extends TrustManagerFactorySpi {
-
- private KeyStore keyStore;
-
- /**
- * @see javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore)
- */
- @Override
- public void engineInit(KeyStore ks) throws KeyStoreException {
- if (ks != null) {
- keyStore = ks;
- } else {
- // BEGIN android-added
- if (System.getProperty("javax.net.ssl.trustStore") == null) {
- String file = System.getProperty("java.home")
- + java.io.File.separator + "etc" + java.io.File.separator
- + "security" + java.io.File.separator
- + "cacerts.bks";
-
- System.setProperty("javax.net.ssl.trustStore", file);
- }
- // END android-added
- keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- String keyStoreName = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.trustStore");
- }
- });
- String keyStorePwd = null;
- if (keyStoreName == null || keyStoreName.equalsIgnoreCase("NONE")
- || keyStoreName.length() == 0) {
- try {
- keyStore.load(null, null);
- } catch (IOException e) {
- throw new KeyStoreException(e);
- } catch (CertificateException e) {
- throw new KeyStoreException(e);
- } catch (NoSuchAlgorithmException e) {
- throw new KeyStoreException(e);
- }
- } else {
- keyStorePwd = AccessController
- .doPrivileged(new java.security.PrivilegedAction<String>() {
- public String run() {
- return System
- .getProperty("javax.net.ssl.trustStorePassword");
- }
- });
- char[] pwd;
- if (keyStorePwd == null) {
- pwd = new char[0];
- } else {
- pwd = keyStorePwd.toCharArray();
- }
- try {
- keyStore.load(new FileInputStream(new File(keyStoreName)), pwd);
- } catch (FileNotFoundException e) {
- throw new KeyStoreException(e);
- } catch (IOException e) {
- throw new KeyStoreException(e);
- } catch (CertificateException e) {
- throw new KeyStoreException(e);
- } catch (NoSuchAlgorithmException e) {
- throw new KeyStoreException(e);
- }
- }
- }
-
- }
-
- /**
- * @see javax.net.ssl#engineInit(ManagerFactoryParameters)
- */
- @Override
- public void engineInit(ManagerFactoryParameters spec)
- throws InvalidAlgorithmParameterException {
- throw new InvalidAlgorithmParameterException(
- "ManagerFactoryParameters not supported");
- }
-
- /**
- * @see javax.net.ssl#engineGetTrustManagers()
- */
- @Override
- public TrustManager[] engineGetTrustManagers() {
- if (keyStore == null) {
- throw new IllegalStateException(
- "TrustManagerFactory is not initialized");
- }
- return new TrustManager[] { new TrustManagerImpl(keyStore) };
- }
-}
diff --git a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java b/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java
deleted file mode 100644
index 543dfb2..0000000
--- a/x-net/src/main/java/org/apache/harmony/xnet/provider/jsse/TrustManagerImpl.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.harmony.xnet.provider.jsse;
-
-import org.bouncycastle.jce.provider.IndexedPKIXParameters;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.cert.CertPathValidator;
-import java.security.cert.CertPathValidatorException;
-import java.security.cert.CertificateException;
-import java.security.cert.CertificateFactory;
-import java.security.cert.PKIXParameters;
-import java.security.cert.TrustAnchor;
-import java.security.cert.X509Certificate;
-import java.util.Arrays;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Set;
-
-import javax.net.ssl.X509TrustManager;
-
-// BEGIN android-added
-import java.lang.reflect.Method;
-import java.security.cert.CertPath;
-import java.security.cert.CertificateEncodingException;
-// END android-added
-
-/**
- *
- * TrustManager implementation. The implementation is based on CertPathValidator
- * PKIX and CertificateFactory X509 implementations. This implementations should
- * be provided by some certification provider.
- *
- * @see javax.net.ssl.X509TrustManager
- */
-public class TrustManagerImpl implements X509TrustManager {
-
- private CertPathValidator validator;
-
- private PKIXParameters params;
-
- private Exception err = null;
-
- private CertificateFactory factory;
-
- /**
- * Creates trust manager implementation
- *
- * @param ks
- */
- public TrustManagerImpl(KeyStore ks) {
- try {
- validator = CertPathValidator.getInstance("PKIX");
- factory = CertificateFactory.getInstance("X509");
- byte[] nameConstrains = null;
- Set<TrustAnchor> trusted = new HashSet<TrustAnchor>();
- for (Enumeration<String> en = ks.aliases(); en.hasMoreElements();) {
- final String alias = en.nextElement();
- final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
- if (cert != null) {
- trusted.add(new TrustAnchor(cert, nameConstrains));
- }
- }
- params = new PKIXParameters(trusted);
- params.setRevocationEnabled(false);
- } catch (Exception e) {
- err = e;
- }
- }
-
-// BEGIN android-added
- /**
- * Indexes trust anchors so they can be found in O(1) instead of O(N) time.
- */
- public void indexTrustAnchors() throws CertificateEncodingException,
- InvalidAlgorithmParameterException, KeyStoreException {
- params = new IndexedPKIXParameters(params.getTrustAnchors());
- params.setRevocationEnabled(false);
- }
-// END android-added
-
- /**
- * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],
- * String)
- */
- public void checkClientTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- if (chain == null || chain.length == 0 || authType == null
- || authType.length() == 0) {
- throw new IllegalArgumentException("null or zero-length parameter");
- }
- if (err != null) {
- throw new CertificateException(err);
- }
- // BEGIN android-added
- // Cater for degenerate special case where we can't
- // establish an actual certificate chain the usual way,
- // but have the peer certificate in our trust store.
- if (isDirectlyTrustedCert(chain)) {
- return;
- }
- // END android-added
- try {
- // BEGIN android-changed
- CertPath certPath = factory.generateCertPath(Arrays.asList(chain));
- if (!Arrays.equals(chain[0].getEncoded(),
- ((X509Certificate)certPath.getCertificates().get(0))
- .getEncoded())) {
- // sanity check failed (shouldn't ever happen, but we are using pretty remote code)
- throw new CertificateException("Certificate chain error");
- }
- validator.validate(certPath, params);
- // END android-changed
- } catch (InvalidAlgorithmParameterException e) {
- throw new CertificateException(e);
- } catch (CertPathValidatorException e) {
- throw new CertificateException(e);
- }
- }
-
- /**
- * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],
- * String)
- */
- public void checkServerTrusted(X509Certificate[] chain, String authType)
- throws CertificateException {
- if (chain == null || chain.length == 0 || authType == null
- || authType.length() == 0) {
- throw new IllegalArgumentException(
- "null or zero-length parameter");
- }
- if (err != null) {
- throw new CertificateException(err);
- }
-// BEGIN android-changed
- CertificateException ce = null;
- try {
- CertPath certPath = factory.generateCertPath(
- Arrays.asList(chain));
- if (!Arrays.equals(chain[0].getEncoded(),
- certPath.getCertificates().get(0).getEncoded())) {
- // Sanity check failed (shouldn't ever happen, but we are
- // using pretty remote code)
- throw new CertificateException("Certificate chain error");
- }
- validator.validate(certPath, params);
- } catch (InvalidAlgorithmParameterException e) {
- ce = new CertificateException(e);
- } catch (CertPathValidatorException e) {
- ce = new CertificateException(e);
- }
- if (ce != null) {
- // Caters to degenerate special case where we can't
- // establish an actual certificate chain the usual way
- // but have the peer certificate in our trust store.
- if (!isDirectlyTrustedCert(chain)) {
- throw ce;
- }
- }
- }
-
- /**
- * Checks whether the given chain is just a certificate
- * that we have in our trust store.
- *
- * @param chain The certificate chain.
- *
- * @return True if the certificate is in our trust store, false otherwise.
- */
- private boolean isDirectlyTrustedCert(X509Certificate[] chain) {
- byte[] questionable;
-
- if (chain.length == 1) {
- if (params instanceof IndexedPKIXParameters) {
- IndexedPKIXParameters index = (IndexedPKIXParameters) params;
- return index.isDirectlyTrusted(chain[0]);
- } else {
- try {
- questionable = chain[0].getEncoded();
- Set<TrustAnchor> anchors = params.getTrustAnchors();
-
- for (TrustAnchor trustAnchor : anchors) {
- byte[] trusted = trustAnchor.getTrustedCert()
- .getEncoded();
- if (Arrays.equals(questionable, trusted)) {
- return true;
- }
- }
- } catch (CertificateEncodingException e) {
- // Ignore.
- }
- }
-
- }
-
- return false;
- }
-// END android-changed
-
- /**
- * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
- */
- public X509Certificate[] getAcceptedIssuers() {
- if (params == null) {
- return new X509Certificate[0];
- }
- Set<TrustAnchor> anchors = params.getTrustAnchors();
- X509Certificate[] certs = new X509Certificate[anchors.size()];
- int i = 0;
- for (Iterator<TrustAnchor> it = anchors.iterator(); it.hasNext();) {
- certs[i++] = it.next().getTrustedCert();
- }
- return certs;
- }
-
-}