Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 
 package com.sun.enterprise.web.connector.grizzly.ssl;
 
SSL over NIO utility class. The class handle the SSLEngine operations needed to support SSL over NIO. This class MUST be executed using an SSLWorkerThread as it rely on some SSLWorkerThread buffers and SSLEngine. TODO: Create an object that Wrap SSLEngine and its associated buffers.

Author(s):
Jeanfrancois Arcand
 
 public class SSLUtils {
    
    
The maximum size a ByteBuffer can take.
 
     public final static int MAX_BB_SIZE = 48 * 4096;
 
     
     /*
      * An empty ByteBuffer used for handshaking
      */
     protected final static ByteBuffer hsBB = ByteBuffer.allocate(0);
   
    
    
The time to wait before timing out when reading bytes
 
     private static int readTimeout = 30000;    
    
    
    
Read encrypted bytes using an SSLEngine.

Parameters:
key The SelectionKey
inputBB The byteBuffer to store encrypted bytes
sslEngine The SSLEngine uses to manage the SSL operations.
timeout The Selector.select() timeout value. A value of 0 will be exectuted as a Selector.selectNow();
Returns:
the bytes read.
 
     public static int doRead(SelectionKey keyByteBuffer inputBB
             SSLEngine sslEngineint timeout){ 
 
        if (key == nullreturn -1;
    	SSLEngineResult result = null;
        int count = 1;
        int byteRead = 0;
        int preReadInputBBPos = inputBB.position();
        Selector readSelector = null;
        SelectionKey tmpKey = null;
        try{
            SocketChannel socketChannel = (SocketChannel)key.channel();
            while (count > 0){
                try {
                    count = socketChannel.read(inputBB);
                } catch(EOFException e) {
                    count = -1;
                }
                
                if (count == -1) {
                    try{
                        sslEngine.closeInbound();  
                    } catch (IOException ex){
                        ;//
                    }
                    return -1;
                }
                byteRead += count;
            }            
            
            if (byteRead == 0 && inputBB.position() == preReadInputBBPos){
                readSelector = SelectorFactory.getSelector();
                if (readSelector == null){
                    return 0;
                }
                count = 1;
                tmpKey = socketChannel
                           .register(readSelector,.);               
                tmpKey.interestOps(tmpKey.interestOps() | .);
                
                int code = 0;
                if (timeout > 0) {
                    code = readSelector.select(timeout);
                } else {
                    code = readSelector.selectNow();
                }
                tmpKey.interestOps(
                    tmpKey.interestOps() & (~.));
                if (code == 0){
                    return 0; // Return on the main Selector and try again.
                }
                while (count > 0){
                    try {
                        count = socketChannel.read(inputBB);
                    } catch(EOFException e) {
                        count = -1;
                    }
                                                    
                    if (count == -1) {
                        try{
                            sslEngine.closeInbound();  
                        } catch (IOException ex){
                            ;//
                        }
                        return -1;
                    }
                    byteRead += count;                    
                }
            } else if (byteRead == 0 && inputBB.position() != preReadInputBBPos) {
                byteRead += (inputBB.position() - preReadInputBBPos);
            }
        } catch (Throwable t){
            Logger logger = SSLSelectorThread.logger();
            if ( logger.isLoggable(.) ){
                logger.log(.,"doRead",t);
            }            
            return -1;
        } finally {
            if (tmpKey != null)
                tmpKey.cancel();
            if (readSelector != null){
                // Bug 6403933
                SelectorFactory.selectNowAndReturnSelector(readSelector);
            }
        }
        return byteRead;
    } 
    

    
Unwrap all encrypted bytes from inputBB to byteBuffer using the SSLEngine

Parameters:
byteBuffer the decrypted ByteBuffer
inputBB the encrypted ByteBuffer
sslEngine The SSLEngine used to manage the SSL operations.
Returns:
the decrypted ByteBuffer
    public static ByteBuffer unwrapAll(ByteBuffer byteBuffer
            ByteBuffer inputBBSSLEngine sslEnginethrows IOException{
        
        SSLEngineResult result = null;
        do{
            try{
               result = unwrap(byteBuffer,inputBB,sslEngine);
            } catch (Throwable ex){
                Logger logger = SSLSelectorThread.logger();
                if ( logger.isLoggable(.) ){
                    logger.log(.,"unwrap",ex);
                }
                inputBB.compact();
            }
            if (result != null){
                switch (result.getStatus()) {
                    case :
                        // Need more data.
                        break;
                    case :
                        if (result.getHandshakeStatus() 
                                == .) {
                            executeDelegatedTask(sslEngine);
                        }
                        break;
                    case :
                         byteBuffer = reallocate(byteBuffer);
                         break;
                    default:                       
                        throw new 
                             IOException("Unwrap error: "result.getStatus());
                 }   
             }
        } while ((inputBB.remaining() > 0) && result!= null &&
                result.getStatus() != .);
        return byteBuffer;
    }
    
    
    
Unwrap available encrypted bytes from inputBB to byteBuffer using the SSLEngine

Parameters:
byteBuffer the decrypted ByteBuffer
inputBB the encrypted ByteBuffer
sslEngine The SSLEngine used to manage the SSL operations.
Returns:
SSLEngineResult of the SSLEngine.unwrap operation.
    public static SSLEngineResult unwrap(ByteBuffer byteBuffer
            ByteBuffer inputBBSSLEngine sslEnginethrows IOException{
        inputBB.flip();
        SSLEngineResult result = sslEngine.unwrap(inputBBbyteBuffer);
        inputBB.compact();
        return result;
    }
    
    
    
Encrypt bytes.

Parameters:
byteBuffer the decrypted ByteBuffer
outputBB the encrypted ByteBuffer
sslEngine The SSLEngine used to manage the SSL operations.
Returns:
SSLEngineResult of the SSLEngine.wrap operation.
    public static SSLEngineResult wrap(ByteBuffer byteBuffer,
            ByteBuffer outputBBSSLEngine sslEnginethrows IOException {        
        
        outputBB.clear();   
        SSLEngineResult result = sslEngine.wrap(byteBufferoutputBB);
        outputBB.flip();
        return result;
    }
    
    
    
Resize a ByteBuffer.
    private static ByteBuffer reallocate(ByteBuffer byteBuffer
            throws IOException{
        
        if (byteBuffer.capacity() > ){
            throw new IOException("Unwrap error: BUFFER_OVERFLOW");
        }
        ByteBuffer tmp = ByteBuffer.allocate(byteBuffer.capacity() * 2);
        byteBuffer.flip();
        tmp.put(byteBuffer);
        byteBuffer = tmp;
        return byteBuffer;
    }
    
     
    
Complete hanshakes operations.

Parameters:
sslEngine The SSLEngine used to manage the SSL operations.
Returns:
SSLEngineResult.HandshakeStatus
    public static SSLEngineResult.HandshakeStatus 
            executeDelegatedTask(SSLEngine sslEngine) {
        Runnable runnable;
        while ((runnable = sslEngine.getDelegatedTask()) != null) {
            runnable.run();
        }
        return sslEngine.getHandshakeStatus();
    }
    
    
    
Perform an SSL handshake using the SSLEngine.

Parameters:
key the SelectionKey
byteBuffer The application ByteBuffer
inputBB The encrypted input ByteBuffer
outputBB The encrypted output ByteBuffer
sslEngine The SSLEngine used.
handshakeStatus The current handshake status
timeout The time the Selector will block waiting for bytes
Returns:
byteBuffer the new ByteBuffer
Throw:
IOException if the handshake fail.
    public static ByteBuffer doHandshake(SelectionKey key,
            ByteBuffer byteBufferByteBuffer inputBBByteBuffer outputBB,
            SSLEngine sslEngineHandshakeStatus handshakeStatus
            throws IOException {
        return doHandshake(key,byteBuffer,inputBB,outputBB,sslEngine,
                           handshakeStatus,);
    }

    
    
Perform an SSL handshake using the SSLEngine.

Parameters:
key the SelectionKey
byteBuffer The application ByteBuffer
inputBB The encrypted input ByteBuffer
outputBB The encrypted output ByteBuffer
sslEngine The SSLEngine used.
handshakeStatus The current handshake status
Returns:
byteBuffer the new ByteBuffer
Throw:
IOException if the handshake fail.
    public static ByteBuffer doHandshake(SelectionKey key,
            ByteBuffer byteBufferByteBuffer inputBBByteBuffer outputBB,
            SSLEngine sslEngineHandshakeStatus handshakeStatus,int timeout
            throws IOException {
        
        SSLEngineResult result;
        int eof = timeout > 0 ? 0 : -1;
        while (handshakeStatus != .){
            switch (handshakeStatus) {
               case :
                    if (doRead(key,inputBB,sslEnginetimeout) <= eof) {
                        try{
                            sslEngine.closeInbound();
                        } catch (IOException ex){
                            Logger logger = SSLSelectorThread.logger();
                            if ( logger.isLoggable(.) ){
                                logger.log(.,"closeInbound",ex);
                            }
                        }
                        throw new EOFException("Connection closed");
                    }
                    
                    while (handshakeStatus == .) {
                        result = unwrap(byteBuffer,inputBB,sslEngine);
                        handshakeStatus = result.getHandshakeStatus();
                        
                        if (result.getStatus() == .){
                            break;
                        }
                        
                        switch (result.getStatus()) {
                            case :
                                switch (handshakeStatus) {
                                    case :
                                        throw new IOException("No Hanshake");
                                    case :
                                        handshakeStatus = 
                                                executeDelegatedTask(sslEngine);
                                        break;                               
                                    case :
                                       return byteBuffer;
                                }
                                break;
                            case :
                                byteBuffer = reallocate(byteBuffer);     
                                break;
                            default
                                throw new IOException("Handshake exception: " + 
                                        result.getStatus());
                        }
                    }  
                    if (handshakeStatus != .) {
                        break;
                    }
                case :
                    result = wrap(,outputBB,sslEngine);
                    handshakeStatus = result.getHandshakeStatus();
                    switch (result.getStatus()) {
                        case :
                            if (handshakeStatus == .) {
                                handshakeStatus = executeDelegatedTask(sslEngine);
                            }
                            // Flush all Server bytes to the client.
                            if (key != null) {
                                OutputWriter.flushChannel(
                                        (SocketChannel)key.channel(), outputBB);
                                outputBB.clear();
                            }
                            break;
                        default
                            throw new IOException("Handshaking error: " 
                                    + result.getStatus());
                        }
                        break;
                default
                    throw new RuntimeException("Invalid Handshaking State" +
                            handshakeStatus);
            } 
        }
        return byteBuffer;
    }
    
    public static int getReadTimeout() {
        return ;
    }
    
    public static void setReadTimeout(int aReadTimeout) {
         = aReadTimeout;
    }
New to GrepCode? Check out our FAQ X