harmony-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ge...@apache.org
Subject svn commit: r423275 [5/7] - in /incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org: ./ apache/ apache/harmony/ apache/harmony/security/ apache/harmony/security/provider/ apache/harmony/security/provider/jsse/
Date Tue, 18 Jul 2006 22:50:14 GMT
Added: incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLRecordProtocol.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLRecordProtocol.java?rev=423275&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLRecordProtocol.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLRecordProtocol.java Tue Jul 18 15:50:12 2006
@@ -0,0 +1,483 @@
+/*
+ *  Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+ *
+ *  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.
+ */
+
+/**
+ * @author Alexander Y. Kleymenov
+ * @version $Revision$
+ */
+
+package org.apache.harmony.security.provider.jsse;
+
+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 paketizes 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 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;
+        } else {
+            return activeReadState.getContentSize(record_size);
+        }
+    }
+
+    /**
+     * Depending on the Connection State (Session) encrypts and compress
+     * the provided data, and packs it into TLSCiphertext structute.
+     * @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 structute.
+     * @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((long) 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;
+    }
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLServerSocketFactoryImpl.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLServerSocketFactoryImpl.java?rev=423275&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLServerSocketFactoryImpl.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLServerSocketFactoryImpl.java Tue Jul 18 15:50:12 2006
@@ -0,0 +1,128 @@
+/*
+ *  Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+ *
+ *  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.
+ */
+
+/**
+ * @author Alexander Y. Kleymenov
+ * @version $Revision$
+ */
+
+package org.apache.harmony.security.provider.jsse;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.ServerSocket;
+import java.security.KeyManagementException;
+import javax.net.ssl.SSLServerSocketFactory;
+
+/**
+ * Implementation of SSLServerSocketFactory.
+ */
+public class SSLServerSocketFactoryImpl extends SSLServerSocketFactory {
+
+    private SSLParameters sslParameters;
+    private IOException instantiationException;
+
+    /**
+     * Constructor.
+     */
+    public SSLServerSocketFactoryImpl() {
+        super();
+        try {
+            this.sslParameters = SSLParameters.getDefault();
+            this.sslParameters.setUseClientMode(false);
+        } catch (KeyManagementException e) {
+            instantiationException =
+                new IOException("Delayed instantiation exception:");
+            instantiationException.initCause(e);
+        }
+    }
+
+    /**
+     * Constructor.
+     */
+    protected SSLServerSocketFactoryImpl(SSLParameters sslParameters) {
+        super();
+        this.sslParameters = (SSLParameters) sslParameters.clone();
+        this.sslParameters.setUseClientMode(false);
+    }
+
+    /**
+     * @see javax.net.ssl.SSLServerSocketFactory#getDefaultCipherSuites()
+     */
+    public String[] getDefaultCipherSuites() {
+        if (instantiationException != null) {
+            return new String[0];
+        }
+        return sslParameters.getEnabledCipherSuites();
+    }
+
+    /**
+     * @see javax.net.ssl.SSLServerSocketFactory#getSupportedCipherSuites()
+     */
+    public String[] getSupportedCipherSuites() {
+        if (instantiationException != null) {
+            return new String[0];
+        }
+        return CipherSuite.getSupportedCipherSuiteNames();
+    }
+
+    /**
+     * @see javax.net.ServerSocketFactory#createServerSocket()
+     */
+    public ServerSocket createServerSocket() throws IOException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLServerSocketImpl((SSLParameters) sslParameters.clone());
+    }
+
+
+    /**
+     * @see javax.net.ServerSocketFactory#createServerSocket(int)
+     */
+    public ServerSocket createServerSocket(int port) throws IOException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLServerSocketImpl(port,
+                (SSLParameters) sslParameters.clone());
+    }
+
+    /**
+     * @see javax.net.ServerSocketFactory#createServerSocket(int,int)
+     */
+    public ServerSocket createServerSocket(int port, int backlog)
+            throws IOException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLServerSocketImpl(port, backlog,
+                (SSLParameters) sslParameters.clone());
+    }
+
+    /**
+     * @see javax.net.ServerSocketFactory#createServerSocket(int,int,InetAddress)
+     */
+    public ServerSocket createServerSocket(int port, int backlog,
+            InetAddress iAddress) throws IOException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLServerSocketImpl(port, backlog, iAddress,
+                (SSLParameters) sslParameters.clone());
+    }
+}
+

Added: incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLServerSocketImpl.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLServerSocketImpl.java?rev=423275&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLServerSocketImpl.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLServerSocketImpl.java Tue Jul 18 15:50:12 2006
@@ -0,0 +1,268 @@
+/*
+ *  Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+ *
+ *  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.
+ */
+
+/**
+ * @author Alexander Y. Kleymenov
+ * @version $Revision$
+ */
+
+package org.apache.harmony.security.provider.jsse;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import javax.net.ssl.SSLServerSocket;
+
+/**
+ * SSLServerSocket implementation
+ * @see javax.net.ssl.SSLServerSocket class documentation for more information.
+ */
+public class SSLServerSocketImpl extends SSLServerSocket {
+
+    // the sslParameters object incapsulates all the info
+    // about supported and 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.
+    private final SSLParameters sslParameters;
+
+    // logger
+    private Logger.Stream logger = Logger.getStream("ssocket");
+
+    /**
+     * Ctor
+     * @param   sslParameters:  SSLParameters
+     * @throws  IOException
+     */
+    protected SSLServerSocketImpl(SSLParameters sslParameters)
+        throws IOException {
+        super();
+        this.sslParameters = sslParameters;
+    }
+
+    /**
+     * Ctor
+     * @param   port:   int
+     * @param   sslParameters:  SSLParameters
+     * @throws  IOException
+     */
+    protected SSLServerSocketImpl(int port, SSLParameters sslParameters)
+        throws IOException {
+        super(port);
+        this.sslParameters = sslParameters;
+    }
+
+    /**
+     * Ctor
+     * @param   port:   int
+     * @param   backlog:    int
+     * @param   sslParameters:  SSLParameters
+     * @throws  IOException
+     */
+    protected SSLServerSocketImpl(int port, int backlog,
+            SSLParameters sslParameters) throws IOException {
+        super(port, backlog);
+        this.sslParameters = sslParameters;
+    }
+
+    /**
+     * Ctor
+     * @param   port:   int
+     * @param   backlog:    int
+     * @param   iAddress:   InetAddress
+     * @param   sslParameters:  SSLParameters
+     * @throws  IOException
+     */
+    protected SSLServerSocketImpl(int port, int backlog,
+                                InetAddress iAddress,
+                                SSLParameters sslParameters)
+        throws IOException {
+        super(port, backlog, iAddress);
+        this.sslParameters = sslParameters;
+    }
+
+    // --------------- SSLParameters based methods ---------------------
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#getSupportedCipherSuites()
+     * method documentation for more information
+     */
+    public String[] getSupportedCipherSuites() {
+        return CipherSuite.getSupportedCipherSuiteNames();
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#getEnabledCipherSuites()
+     * method documentation for more information
+     */
+    public String[] getEnabledCipherSuites() {
+        return sslParameters.getEnabledCipherSuites();
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#setEnabledCipherSuites(String[])
+     * method documentation for more information
+     */
+    public void setEnabledCipherSuites(String[] suites) {
+        sslParameters.setEnabledCipherSuites(suites);
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#getSupportedProtocols()
+     * method documentation for more information
+     */
+    public String[] getSupportedProtocols() {
+        return (String[]) ProtocolVersion.supportedProtocols.clone();
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#getEnabledProtocols()
+     * method documentation for more information
+     */
+    public String[] getEnabledProtocols() {
+        return sslParameters.getEnabledProtocols();
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#setEnabledProtocols(String[])
+     * method documentation for more information
+     */
+    public void setEnabledProtocols(String[] protocols) {
+        sslParameters.setEnabledProtocols(protocols);
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#setUseClientMode(boolean)
+     * method documentation for more information
+     */
+    public void setUseClientMode(boolean mode) {
+        sslParameters.setUseClientMode(mode);
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#getUseClientMode()
+     * method documentation for more information
+     */
+    public boolean getUseClientMode() {
+        return sslParameters.getUseClientMode();
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#setNeedClientAuth(boolean)
+     * method documentation for more information
+     */
+    public void setNeedClientAuth(boolean need) {
+        sslParameters.setNeedClientAuth(need);
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#getNeedClientAuth()
+     * method documentation for more information
+     */
+    public boolean getNeedClientAuth() {
+        return sslParameters.getNeedClientAuth();
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#setWantClientAuth(boolean)
+     * method documentation for more information
+     */
+    public void setWantClientAuth(boolean want) {
+        sslParameters.setWantClientAuth(want);
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#getWantClientAuth()
+     * method documentation for more information
+     */
+    public boolean getWantClientAuth() {
+        return sslParameters.getWantClientAuth();
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#setEnableSessionCreation(boolean)
+     * method documentation for more information
+     */
+    public void setEnableSessionCreation(boolean flag) {
+        sslParameters.setEnableSessionCreation(flag);
+    }
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see javax.net.ssl.SSLServerSocket#getEnableSessionCreation()
+     * method documentation for more information
+     */
+    public boolean getEnableSessionCreation() {
+        return sslParameters.getEnableSessionCreation();
+    }
+
+
+    // ------------- ServerSocket's methods overridings ----------------
+
+    /**
+     * This method works according to the specification of implemented class.
+     * @see java.net.ServerSocket#accept()
+     * method documentation for more information
+     */
+    public Socket accept() throws IOException {
+        if (logger != null) {
+            logger.println("SSLServerSocketImpl.accept ..");
+        }
+        SSLSocketImpl s = new SSLSocketImpl(
+                (SSLParameters) sslParameters.clone());
+        implAccept(s);
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            try {
+                sm.checkAccept(s.getInetAddress().getHostAddress(),
+                        s.getPort());
+            } catch(SecurityException e) {
+                s.close();
+                throw e;
+            }
+        }
+        s.init();
+        s.startHandshake();
+        if (logger != null) {
+            logger.println("SSLServerSocketImpl: accepted, initialized");
+        }
+        return s;
+    }
+
+    /**
+     * Returns the string representation of the object.
+     */
+    public String toString() {
+        return "[SSLServerSocketImpl]";
+    }
+
+    // -----------------------------------------------------------------
+}
+

Added: incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSessionContextImpl.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSessionContextImpl.java?rev=423275&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSessionContextImpl.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSessionContextImpl.java Tue Jul 18 15:50:12 2006
@@ -0,0 +1,159 @@
+/*
+ *  Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+ *
+ *  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.
+ */
+
+/**
+ * @author Boris Kuznetsov
+ * @version $Revision$
+ */
+package org.apache.harmony.security.provider.jsse;
+
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.Hashtable;
+
+import javax.net.ssl.SSLSession;
+import javax.net.ssl.SSLSessionContext;
+
+/**
+ * 
+ * SSLSessionContext implementation
+ * @see javax.net.ssl.SSLSessionContext
+ */
+public class SSLSessionContextImpl implements SSLSessionContext {
+
+    private int cacheSize = 0;
+
+    private long timeout = 0;
+
+    private final Hashtable sessions = new Hashtable();
+
+    /**
+     * 
+     * @see javax.net.ssl.SSLSessionContext.getIds()
+     */
+    public Enumeration getIds() {
+        return new Enumeration() {
+            Enumeration keys = sessions.keys();
+            public boolean hasMoreElements() {
+                return keys.hasMoreElements();
+            }
+            public Object nextElement() {
+                return ((IdKey)keys.nextElement()).id;
+            }
+        };
+    }
+
+    /**
+     *
+     * @see javax.net.ssl.SSLSessionContext.getSession(byte[] sessionId)
+     */
+    public SSLSession getSession(byte[] sessionId) {      
+        return (SSLSession) sessions.get(new IdKey(sessionId));
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSessionContext.getSessionCacheSize()
+     */
+    public int getSessionCacheSize() {
+        return cacheSize;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSessionContext.getSessionTimeout()
+     */
+    public int getSessionTimeout() {
+        return (int)(timeout/1000);
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSessionContext.setSessionCacheSize(int size)
+     */
+    public void setSessionCacheSize(int size) throws IllegalArgumentException {
+        if (size < 0) {
+            throw new IllegalArgumentException("size < 0");
+        }
+        cacheSize = size;
+        if (size > 0 && sessions.size() < size) {
+            // remove size-sessions.size() oldest sessions
+            removeOldest(size - sessions.size());
+        }
+
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSessionContext.setSessionTimeout(int seconds)
+     */
+    public void setSessionTimeout(int seconds) throws IllegalArgumentException {
+        if (seconds < 0) {
+            throw new IllegalArgumentException("seconds < 0");
+        }
+        timeout = seconds * 1000;
+
+        // Check timeouts and remome expired sessions
+        SSLSessionImpl ses;
+        for (Enumeration en = sessions.keys(); en.hasMoreElements();) {
+            ses = (SSLSessionImpl)(sessions.get(en.nextElement()));
+            if (!ses.isValid()) {
+                sessions.remove(ses.getId());
+            }
+        }
+    }
+
+    /**
+     * Adds session to the session cach
+     * @param ses
+     */
+    void putSession(SSLSessionImpl ses) {
+        if (cacheSize > 0 && sessions.size() == cacheSize) {
+            // remove 1 oldest session
+            removeOldest(1);
+        }
+        ses.context = this;
+        sessions.put(new IdKey(ses.getId()), ses);
+    }
+
+    // removes invalidated/oldest sessions from the session cache
+    private void removeOldest(int num) {
+        //TODO
+        // ses.context = null;
+    }
+    
+    private class IdKey {
+        private byte[] id;
+        
+        private IdKey(byte[] id) {
+            this.id = id;
+        }
+        
+        public boolean equals(Object o) {
+            if (!(o instanceof IdKey)) {
+                return false;
+            }
+            return Arrays.equals(id, ((IdKey)o).id);
+        }
+        
+        public int hashCode() {
+            // TODO uncomment for 1.5
+            // return Arrays.hashCode(id);
+            int hash = 0;
+            for (int i = 0; i < id.length; i++) {
+                hash += id[i];
+            }
+            return hash;
+        }
+    }
+
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSessionImpl.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSessionImpl.java?rev=423275&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSessionImpl.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSessionImpl.java Tue Jul 18 15:50:12 2006
@@ -0,0 +1,408 @@
+/*
+ *  Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+ *
+ *  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.
+ */
+
+/**
+ * @author Boris Kuznetsov
+ * @version $Revision$
+ */
+
+package org.apache.harmony.security.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.Iterator;
+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 org.apache.harmony.security.utils.TwoKeyHashMap;
+
+/**
+ * 
+ * SSLSession implementation
+ *
+ * @see javax.net.ssl.SSLSession
+ */
+public class SSLSessionImpl implements SSLSession {
+
+    /**
+     * Session object reporting an invalid cipher suite of 
+     * "SSL_NULL_WITH_NULL_NULL"
+     */
+    public static final SSLSessionImpl NULL_SESSION = new SSLSessionImpl(null);
+
+    private long creationTime;
+    private boolean isValid = true;
+    private TwoKeyHashMap values = new TwoKeyHashMap();
+    
+    /**
+     * 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
+     */
+    SSLSessionContextImpl context;
+    
+    
+    /**
+     * certificates were sent to the peer 
+     */
+    X509Certificate[] localCertificates;
+    
+    /**
+     * Peer certificates
+     */
+    X509Certificate[] peerCertificates;
+    
+    /**
+     * Peer host name 
+     */
+    String peerHost;
+    
+    /**
+     * Peer port number
+     */
+    int peerPort = -1;
+    
+    /**
+     * Master secret
+     */
+    byte[] master_secret;
+    
+    
+    /**
+     * clientRandom
+     */
+    byte[] clientRandom;
+    
+    /**
+     * serverRandom
+     */
+    byte[] serverRandom;
+    
+    /**
+     * True if this entity is considered the server
+     */
+    boolean isServer = false;
+
+    /**
+     * 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;
+        } else {
+            this.cipherSuite = cipher_suite;
+            id = new byte[32];
+            sr.nextBytes(id);
+            long time = new java.util.Date().getTime() / 1000;
+            id[28] = (byte) ((time & 0xFF000000) >>> 24);
+            id[29] = (byte) ((time & 0xFF0000) >>> 16);
+            id[30] = (byte) ((time & 0xFF00) >>> 8);
+            id[31] = (byte) (time & 0xFF);
+            isServer = true;
+        }
+
+    }
+
+    /**
+     * Creates SSLSession implementation
+     * @param sr
+     */
+    public SSLSessionImpl(SecureRandom sr) {
+        this(null, sr);
+    }
+
+    private SSLSessionImpl() {
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getApplicationBufferSize()
+     */
+    public int getApplicationBufferSize() {
+        return SSLRecordProtocol.MAX_DATA_LENGTH;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getCipherSuite()
+     */
+    public String getCipherSuite() {
+        return cipherSuite.getName();
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getCreationTime()
+     */
+    public long getCreationTime() {
+        return creationTime;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getId()
+     */
+    public byte[] getId() {
+        return id;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getLastAccessedTime()
+     */
+    public long getLastAccessedTime() {
+        return lastAccessedTime;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getLocalCertificates()
+     */
+    public Certificate[] getLocalCertificates() {
+        return localCertificates;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getLocalPrincipal()
+     */
+    public Principal getLocalPrincipal() {
+        if (localCertificates != null && localCertificates.length > 0) {
+            return localCertificates[0].getSubjectX500Principal();
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getPacketBufferSize()
+     */
+    public int getPacketBufferSize() {
+        return SSLRecordProtocol.MAX_SSL_PACKET_SIZE;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getPeerCertificateChain()
+     */
+    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;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getPeerCertificates()
+     */
+    public Certificate[] getPeerCertificates()
+            throws SSLPeerUnverifiedException {
+        if (peerCertificates == null) {
+            throw new SSLPeerUnverifiedException("No peer certificate");
+        }
+        return peerCertificates;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getPeerHost()
+     */
+    public String getPeerHost() {
+        return peerHost;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getPeerPort()
+     */
+    public int getPeerPort() {
+        return peerPort;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getPeerPrincipal()
+     */
+    public Principal getPeerPrincipal() throws SSLPeerUnverifiedException {
+        if (peerCertificates == null) {
+            throw new SSLPeerUnverifiedException("No peer certificate");
+        }
+        return peerCertificates[0].getSubjectX500Principal();
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getProtocol()
+     */
+    public String getProtocol() {
+        return protocol.name;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getSessionContext()
+     */
+    public SSLSessionContext getSessionContext() {
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            sm.checkPermission(new SSLPermission("getSSLSessionContext"));
+        }
+        return context;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getValue(String name)
+     */
+    public Object getValue(String name) {
+        if (name == null) {
+            throw new IllegalArgumentException("Parameter is null");
+        }
+        return values.get(name, AccessController.getContext());
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.getValueNames()
+     */
+    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]);
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.invalidate()
+     */
+    public void invalidate() {
+        isValid = false;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.isValid()
+     */
+    public boolean isValid() {
+        if (isValid
+                && context != null
+                && context.getSessionTimeout() != 0
+                && lastAccessedTime + context.getSessionTimeout() > System
+                        .currentTimeMillis()) {
+            isValid = false;
+        }
+        return isValid;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.putValue(String name, Object value)
+     */
+    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 != null && old instanceof SSLSessionBindingListener) {
+            ((SSLSessionBindingListener) old)
+                    .valueUnbound(new SSLSessionBindingEvent(this, name));
+        }
+
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSession.removeValue(String name)
+     */
+    public void removeValue(String name) {
+        if (name == null) {
+            throw new IllegalArgumentException("Parameter is null");
+        }
+        values.remove(name, AccessController.getContext());
+
+    }
+
+    public Object clone() {
+        SSLSessionImpl ses = new SSLSessionImpl();
+        ses.id = this.id;
+        ses.creationTime = this.creationTime;
+        ses.lastAccessedTime = this.lastAccessedTime;
+        ses.isValid = this.isValid;
+        ses.cipherSuite = this.cipherSuite;
+        ses.localCertificates = this.localCertificates;
+        ses.peerCertificates = this.peerCertificates;
+        ses.master_secret = this.master_secret;
+        ses.clientRandom = this.clientRandom;
+        ses.serverRandom = this.serverRandom;
+        ses.peerHost = this.peerHost;
+        ses.peerPort = this.peerPort;
+        ses.isServer = this.isServer;
+        ses.context = this.context;
+        ses.protocol = this.protocol;
+        ses.values = this.values;
+        return ses;
+    }
+
+
+    /**
+     * Sets the address of the peer
+     * @param peerHost
+     * @param peerPort
+     */
+    void setPeer(String peerHost, int peerPort) {
+        this.peerHost = peerHost;
+        this.peerPort = peerPort;
+    }
+}

Added: incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSocketFactoryImpl.java
URL: http://svn.apache.org/viewvc/incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSocketFactoryImpl.java?rev=423275&view=auto
==============================================================================
--- incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSocketFactoryImpl.java (added)
+++ incubator/harmony/enhanced/classlib/trunk/modules/x-net/src/main/java/org/apache/harmony/security/provider/jsse/SSLSocketFactoryImpl.java Tue Jul 18 15:50:12 2006
@@ -0,0 +1,157 @@
+/*
+ *  Copyright 2006 The Apache Software Foundation or its licensors, as applicable.
+ *
+ *  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.
+ */
+
+/**
+ * @author Alexander Y. Kleymenov
+ * @version $Revision$
+ */
+
+package org.apache.harmony.security.provider.jsse;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.security.KeyManagementException;
+
+import javax.net.ssl.SSLSocketFactory;
+
+/**
+ * Implementation of SSLSocketFactory.
+ */
+public class SSLSocketFactoryImpl extends SSLSocketFactory {
+
+    private SSLParameters sslParameters;
+    private IOException instantiationException;
+
+    /**
+     * Constructor.
+     */
+    public SSLSocketFactoryImpl() {
+        super();
+        try {
+            sslParameters = SSLParameters.getDefault();
+        } catch (KeyManagementException e) {
+            instantiationException =
+                new IOException("Delayed instantiation exception:");
+            instantiationException.initCause(e);
+        }
+    }
+
+    /**
+     * Constructor.
+     */
+    protected SSLSocketFactoryImpl(SSLParameters sslParameters) {
+        super();
+        this.sslParameters = sslParameters;
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSocketFactory#getDefaultCipherSuites()
+     */
+    public String[] getDefaultCipherSuites() {
+        if (instantiationException != null) {
+            return new String[0];
+        }
+        return sslParameters.getEnabledCipherSuites();
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSocketFactory#getSupportedCipherSuites()
+     */
+    public String[] getSupportedCipherSuites() {
+        if (instantiationException != null) {
+            return new String[0];
+        }
+        return CipherSuite.getSupportedCipherSuiteNames();
+    }
+
+    /**
+     * @see javax.net.ssl.SSLSocketFactory#createSocket(Socket,String,int,boolean)
+     */
+    public Socket createSocket(Socket s, String host, int port,
+            boolean autoClose) throws IOException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLSocketWrapper(s, autoClose, (SSLParameters) sslParameters
+                .clone());
+    }
+
+    // -------------- Methods inherided from SocketFactory --------------
+
+    /**
+     * @see javax.net.SocketFactory#createSocket()
+     */
+    public Socket createSocket() throws IOException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLSocketImpl((SSLParameters) sslParameters.clone());
+    }
+
+    /**
+     * @see javax.net.SocketFactory#createSocket(String,int)
+     */
+    public Socket createSocket(String host, int port)
+            throws IOException, UnknownHostException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLSocketImpl(host, port,
+                (SSLParameters) sslParameters.clone());
+    }
+
+    /**
+     * @see javax.net.SocketFactory#createSocket(String,int,InetAddress,int)
+     */
+    public Socket createSocket(String host, int port,
+            InetAddress localHost, int localPort) throws IOException,
+            UnknownHostException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLSocketImpl(host, port, localHost, localPort,
+                (SSLParameters) sslParameters.clone());
+    }
+
+    /**
+     * @see javax.net.SocketFactory#createSocket(InetAddress,int)
+     */
+    public Socket createSocket(InetAddress host, int port)
+            throws IOException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLSocketImpl(host, port,
+                (SSLParameters) sslParameters.clone());
+    }
+
+    /**
+     * @see javax.net.SocketFactory#createSocket(InetAddress,int,InetAddress,int)
+     */
+    public Socket createSocket(InetAddress address, int port,
+            InetAddress localAddress, int localPort) throws IOException {
+        if (instantiationException != null) {
+            throw instantiationException;
+        }
+        return new SSLSocketImpl(address, port, localAddress, localPort,
+                (SSLParameters) sslParameters.clone());
+    }
+
+    // ------------------------------------------------------------------
+}
+



Mime
View raw message