Java Code Examples for javax.net.ssl.SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING

The following examples show how to use javax.net.ssl.SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SSLSocketChannel2.java    From ans-android-sdk with GNU General Public License v3.0 6 votes vote down vote up
/**
 * performs the unwrap operation by unwrapping from {@link #inCrypt} to {@link #inData}
 **/
private synchronized ByteBuffer unwrap() throws SSLException {
    int rem;
    //There are some ssl test suites, which get around the selector.select() call, which
    // cause an infinite unwrap and 100% cpu usage (see #459 and #458)
    if (readEngineResult.getStatus() == Status.CLOSED
            && sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) {
        try {
            close();
        } catch (IOException e) {
            //Not really interesting
        }
    }
    do {
        rem = inData.remaining();
        readEngineResult = sslEngine.unwrap(inCrypt, inData);
    } while (readEngineResult.getStatus() == Status.OK && (rem != inData.remaining()
            || sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP));
    inData.flip();
    return inData;
}
 
Example 2
Source File: SSLSocketChannel2.java    From clevertap-android-sdk with MIT License 6 votes vote down vote up
/**
 * performs the unwrap operation by unwrapping from {@link #inCrypt} to {@link #inData}
 **/
private synchronized ByteBuffer unwrap() throws SSLException {
    int rem;
    //There are some ssl test suites, which get around the selector.select() call, which cause an infinite unwrap and 100% cpu usage (see #459 and #458)
    if(readEngineResult.getStatus() == SSLEngineResult.Status.CLOSED && sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING){
        try {
            close();
        } catch (IOException e) {
            //Not really interesting
        }
    }
    do {
        rem = inData.remaining();
        readEngineResult = sslEngine.unwrap( inCrypt, inData );
    } while ( readEngineResult.getStatus() == SSLEngineResult.Status.OK && ( rem != inData.remaining() || sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP ) );
    inData.flip();
    return inData;
}
 
Example 3
Source File: SSLSocketChannel2.java    From RipplePower with Apache License 2.0 6 votes vote down vote up
/**
 * performs the unwrap operation by unwrapping from {@link #inCrypt} to {@link #inData}
 **/
private synchronized ByteBuffer unwrap() throws SSLException {
	int rem;
	//There are some ssl test suites, which get around the selector.select() call, which cause an infinite unwrap and 100% cpu usage (see #459 and #458)
	if(readEngineResult.getStatus() == SSLEngineResult.Status.CLOSED && sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING){
		try {
			close();
		} catch (IOException e) {
			//Not really interesting
		}
	}
	do {
		rem = inData.remaining();
		readEngineResult = sslEngine.unwrap( inCrypt, inData );
	} while ( readEngineResult.getStatus() == SSLEngineResult.Status.OK && ( rem != inData.remaining() || sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP ) );
	inData.flip();
	return inData;
}
 
Example 4
Source File: TransportContext.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
HandshakeStatus getHandshakeStatus() {
    if (!outputRecord.isEmpty()) {
        // If no handshaking, special case to wrap alters or
        // post-handshake messages.
        return HandshakeStatus.NEED_WRAP;
    } else if (isOutboundClosed() && isInboundClosed()) {
        return HandshakeStatus.NOT_HANDSHAKING;
    } else if (handshakeContext != null) {
        if (!handshakeContext.delegatedActions.isEmpty()) {
            return HandshakeStatus.NEED_TASK;
        } else if (!isInboundClosed()) {
            if (sslContext.isDTLS() &&
                    !inputRecord.isEmpty()) {
                return HandshakeStatus.NEED_UNWRAP_AGAIN;
            } else {
                return HandshakeStatus.NEED_UNWRAP;
            }
        } else if (!isOutboundClosed()) {
            // Special case that the inbound was closed, but outbound open.
            return HandshakeStatus.NEED_WRAP;
        }   // Otherwise, both inbound and outbound are closed.
    }

    return HandshakeStatus.NOT_HANDSHAKING;
}
 
Example 5
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SSLStreams.WrapperResult sendData(ByteBuffer src) throws IOException {
   SSLStreams.WrapperResult r = null;

   while(src.remaining() > 0) {
      r = this.wrapper.wrapAndSend(src);
      Status status = r.result.getStatus();
      if (status == Status.CLOSED) {
         this.doClosure();
         return r;
      }

      HandshakeStatus hs_status = r.result.getHandshakeStatus();
      if (hs_status != HandshakeStatus.FINISHED && hs_status != HandshakeStatus.NOT_HANDSHAKING) {
         this.doHandshake(hs_status);
      }
   }

   return r;
}
 
Example 6
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SSLStreams.WrapperResult sendData(ByteBuffer src) throws IOException {
   SSLStreams.WrapperResult r = null;

   while(src.remaining() > 0) {
      r = this.wrapper.wrapAndSend(src);
      Status status = r.result.getStatus();
      if (status == Status.CLOSED) {
         this.doClosure();
         return r;
      }

      HandshakeStatus hs_status = r.result.getHandshakeStatus();
      if (hs_status != HandshakeStatus.FINISHED && hs_status != HandshakeStatus.NOT_HANDSHAKING) {
         this.doHandshake(hs_status);
      }
   }

   return r;
}
 
Example 7
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public SSLStreams.WrapperResult sendData(ByteBuffer src) throws IOException {
   SSLStreams.WrapperResult r = null;

   while(src.remaining() > 0) {
      r = this.wrapper.wrapAndSend(src);
      Status status = r.result.getStatus();
      if (status == Status.CLOSED) {
         this.doClosure();
         return r;
      }

      HandshakeStatus hs_status = r.result.getHandshakeStatus();
      if (hs_status != HandshakeStatus.FINISHED && hs_status != HandshakeStatus.NOT_HANDSHAKING) {
         this.doHandshake(hs_status);
      }
   }

   return r;
}
 
Example 8
Source File: TransportContext.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
HandshakeStatus getHandshakeStatus() {
    if (!outputRecord.isEmpty()) {
        // If no handshaking, special case to wrap alters or
        // post-handshake messages.
        return HandshakeStatus.NEED_WRAP;
    } else if (isOutboundClosed() && isInboundClosed()) {
        return HandshakeStatus.NOT_HANDSHAKING;
    } else if (handshakeContext != null) {
        if (!handshakeContext.delegatedActions.isEmpty()) {
            return HandshakeStatus.NEED_TASK;
        } else if (!isInboundClosed()) {
              //JDK8 NEED_UNWRAP returnned for NEED_UNWRAP_AGAIN status
              // needUnwrapAgain should be used to determine NEED_UNWRAP_AGAIN
            return HandshakeStatus.NEED_UNWRAP;
        } else if (!isOutboundClosed()) {
            // Special case that the inbound was closed, but outbound open.
            return HandshakeStatus.NEED_WRAP;
        }
    } else if (isOutboundClosed() && !isInboundClosed()) {
        // Special case that the outbound was closed, but inbound open.
        return HandshakeStatus.NEED_UNWRAP;
    } else if (!isOutboundClosed() && isInboundClosed()) {
        // Special case that the inbound was closed, but outbound open.
        return HandshakeStatus.NEED_WRAP;
    }

    return HandshakeStatus.NOT_HANDSHAKING;
}
 
Example 9
Source File: SslHandler.java    From jane with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void renegotiateIfNeeded(NextFilter nextFilter, SSLEngineResult res) throws Exception {
	if (res.getStatus() != Status.CLOSED && res.getStatus() != Status.BUFFER_UNDERFLOW
			&& res.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
		// Renegotiation required.
		handshakeComplete = false;
		handshakeStatus = res.getHandshakeStatus();
		handshake(nextFilter);
	}
}
 
Example 10
Source File: SSLProtocol.java    From jolie with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void handshake()
	throws IOException {
	if( firstTime ) {
		init();
		sslEngine.beginHandshake();
		firstTime = false;
	}

	boolean keepRun = true;

	Runnable runnable;
	while( keepRun
		&& sslEngine.getHandshakeStatus() != HandshakeStatus.FINISHED
		&& sslEngine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING ) {
		switch( sslEngine.getHandshakeStatus() ) {
		case NEED_TASK:
			while( (runnable = sslEngine.getDelegatedTask()) != null ) {
				runnable.run();
			}
			break;
		case NEED_WRAP:
			wrap( ByteBuffer.allocate( INITIAL_BUFFER_SIZE ) );
			break;
		case NEED_UNWRAP:
			keepRun = unwrap( null );
			if( sslEngine.isInboundDone() && sslEngine.isOutboundDone() ) {
				keepRun = false;
			}
			break;
		}
	}
}
 
Example 11
Source File: SSLSocketChannel2.java    From clevertap-android-sdk with MIT License 4 votes vote down vote up
/**
 * This method will do whatever necessary to process the sslengine handshake.
 * Thats why it's called both from the {@link #read(ByteBuffer)} and {@link #write(ByteBuffer)}
 **/
private synchronized void processHandshake() throws IOException {
    if( sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING )
        return; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking.
    if( !tasks.isEmpty() ) {
        Iterator<Future<?>> it = tasks.iterator();
        while ( it.hasNext() ) {
            Future<?> f = it.next();
            if( f.isDone() ) {
                it.remove();
            } else {
                if( isBlocking() )
                    consumeFutureUninterruptible( f );
                return;
            }
        }
    }

    if( sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP ) {
        if( !isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW ) {
            inCrypt.compact();
            int read = socketChannel.read( inCrypt );
            if( read == -1 ) {
                throw new IOException( "connection closed unexpectedly by peer" );
            }
            inCrypt.flip();
        }
        inData.compact();
        unwrap();
        if( readEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) {
            createBuffers( sslEngine.getSession() );
            return;
        }
    }
    consumeDelegatedTasks();
    if( tasks.isEmpty() || sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP ) {
        socketChannel.write( wrap( emptybuffer ) );
        if( writeEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) {
            createBuffers( sslEngine.getSession() );
            return;
        }
    }
    assert ( sslEngine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING );// this function could only leave NOT_HANDSHAKING after createBuffers was called unless #190 occurs which means that nio wrap/unwrap never return HandshakeStatus.FINISHED

    bufferallocations = 1; // look at variable declaration why this line exists and #190. Without this line buffers would not be be recreated when #190 AND a rehandshake occur.
}
 
Example 12
Source File: SslHandler.java    From netty-4.1.22 with Apache License 2.0 4 votes vote down vote up
/**
 * This method will not call
 * {@link #setHandshakeFailure(ChannelHandlerContext, Throwable, boolean, boolean, boolean)} or
 * {@link #setHandshakeFailure(ChannelHandlerContext, Throwable)}.
 * @return {@code true} if this method ends on {@link SSLEngineResult.HandshakeStatus#NOT_HANDSHAKING}.
 */
private boolean wrapNonAppData(ChannelHandlerContext ctx, boolean inUnwrap) throws SSLException {
    ByteBuf out = null;
    ByteBufAllocator alloc = ctx.alloc();
    try {
        // Only continue to loop if the handler was not removed in the meantime.
        // See https://github.com/netty/netty/issues/5860
        while (!ctx.isRemoved()) {
            if (out == null) {
                // As this is called for the handshake we have no real idea how big the buffer needs to be.
                // That said 2048 should give us enough room to include everything like ALPN / NPN data.
                // If this is not enough we will increase the buffer in wrap(...).
                out = allocateOutNetBuf(ctx, 2048, 1);
            }
            SSLEngineResult result = wrap(alloc, engine, Unpooled.EMPTY_BUFFER, out);

            if (result.bytesProduced() > 0) {
                ctx.write(out);
                if (inUnwrap) {
                    needsFlush = true;
                }
                out = null;
            }

            switch (result.getHandshakeStatus()) {
                case FINISHED:
                    setHandshakeSuccess();
                    return false;
                case NEED_TASK:
                    runDelegatedTasks();
                    break;
                case NEED_UNWRAP:
                    if (inUnwrap) {
                        // If we asked for a wrap, the engine requested an unwrap, and we are in unwrap there is
                        // no use in trying to call wrap again because we have already attempted (or will after we
                        // return) to feed more data to the engine.
                        return false;
                    }

                    unwrapNonAppData(ctx);
                    break;
                case NEED_WRAP:
                    break;
                case NOT_HANDSHAKING:
                    setHandshakeSuccessIfStillHandshaking();
                    // Workaround for TLS False Start problem reported at:
                    // https://github.com/netty/netty/issues/1108#issuecomment-14266970
                    if (!inUnwrap) {
                        unwrapNonAppData(ctx);
                    }
                    return true;
                default:
                    throw new IllegalStateException("Unknown handshake status: " + result.getHandshakeStatus());
            }

            if (result.bytesProduced() == 0) {
                break;
            }

            // It should not consume empty buffers when it is not handshaking
            // Fix for Android, where it was encrypting empty buffers even when not handshaking
            if (result.bytesConsumed() == 0 && result.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING) {
                break;
            }
        }
    }  finally {
        if (out != null) {
            out.release();
        }
    }
    return false;
}
 
Example 13
Source File: ExportControlled.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Perform the handshaking step of the TLS connection. We use the `sslEngine' along with the `channel' to exchange messages with the server to setup an
 * encrypted channel.
 * 
 * @param sslEngine
 *            {@link SSLEngine}
 * @param channel
 *            {@link AsynchronousSocketChannel}
 * @throws SSLException
 *             in case of handshake error
 */
private static void performTlsHandshake(SSLEngine sslEngine, AsynchronousSocketChannel channel) throws SSLException {
    sslEngine.beginHandshake();
    HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus();

    // Create byte buffers to use for holding application data
    int packetBufferSize = sslEngine.getSession().getPacketBufferSize();
    ByteBuffer myNetData = ByteBuffer.allocate(packetBufferSize);
    ByteBuffer peerNetData = ByteBuffer.allocate(packetBufferSize);
    int appBufferSize = sslEngine.getSession().getApplicationBufferSize();
    ByteBuffer myAppData = ByteBuffer.allocate(appBufferSize);
    ByteBuffer peerAppData = ByteBuffer.allocate(appBufferSize);

    SSLEngineResult res = null;

    while (handshakeStatus != HandshakeStatus.FINISHED && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING) {
        switch (handshakeStatus) {
            case NEED_WRAP:
                myNetData.clear();
                res = sslEngine.wrap(myAppData, myNetData);
                handshakeStatus = res.getHandshakeStatus();
                switch (res.getStatus()) {
                    case OK:
                        myNetData.flip();
                        write(channel, myNetData);
                        break;
                    case BUFFER_OVERFLOW:
                    case BUFFER_UNDERFLOW:
                    case CLOSED:
                        throw new CJCommunicationsException("Unacceptable SSLEngine result: " + res);
                }
                break;
            case NEED_UNWRAP:
                peerNetData.flip(); // Process incoming handshaking data
                res = sslEngine.unwrap(peerNetData, peerAppData);
                handshakeStatus = res.getHandshakeStatus();
                switch (res.getStatus()) {
                    case OK:
                        peerNetData.compact();
                        break;
                    case BUFFER_OVERFLOW:
                        // Check if we need to enlarge the peer application data buffer.
                        final int newPeerAppDataSize = sslEngine.getSession().getApplicationBufferSize();
                        if (newPeerAppDataSize > peerAppData.capacity()) {
                            // enlarge the peer application data buffer
                            ByteBuffer newPeerAppData = ByteBuffer.allocate(newPeerAppDataSize);
                            newPeerAppData.put(peerAppData);
                            newPeerAppData.flip();
                            peerAppData = newPeerAppData;
                        } else {
                            peerAppData.compact();
                        }
                        break;
                    case BUFFER_UNDERFLOW:
                        // Check if we need to enlarge the peer network packet buffer
                        final int newPeerNetDataSize = sslEngine.getSession().getPacketBufferSize();
                        if (newPeerNetDataSize > peerNetData.capacity()) {
                            // enlarge the peer network packet buffer
                            ByteBuffer newPeerNetData = ByteBuffer.allocate(newPeerNetDataSize);
                            newPeerNetData.put(peerNetData);
                            newPeerNetData.flip();
                            peerNetData = newPeerNetData;
                        } else {
                            peerNetData.compact();
                        }
                        // obtain more inbound network data and then retry the operation
                        if (read(channel, peerNetData) < 0) {
                            throw new CJCommunicationsException("Server does not provide enough data to proceed with SSL handshake.");
                        }
                        break;
                    case CLOSED:
                        throw new CJCommunicationsException("Unacceptable SSLEngine result: " + res);
                }
                break;

            case NEED_TASK:
                sslEngine.getDelegatedTask().run();
                handshakeStatus = sslEngine.getHandshakeStatus();
                break;
            case FINISHED:
            case NOT_HANDSHAKING:
                break;
        }
    }
}
 
Example 14
Source File: SslConnection.java    From WebSocket-for-Android with Apache License 2.0 4 votes vote down vote up
public Connection handle() throws IOException
{
    try
    {
        allocateBuffers();

        boolean progress=true;

        while (progress)
        {
            progress=false;

            // If we are handshook let the delegate connection
            if (_engine.getHandshakeStatus()!=HandshakeStatus.NOT_HANDSHAKING)
                progress=process(null,null);

            // handle the delegate connection
            AsyncConnection next = (AsyncConnection)_connection.handle();
            if (next!=_connection && next!=null)
            {
                _connection=next;
                progress=true;
            }

            _logger.debug("{} handle {} progress={}", _session, this, progress);
        }
    }
    finally
    {
        releaseBuffers();

        if (!_ishut && _sslEndPoint.isInputShutdown() && _sslEndPoint.isOpen())
        {
            _ishut=true;
            try
            {
                _connection.onInputShutdown();
            }
            catch(Throwable x)
            {
                _logger.warn("onInputShutdown failed", x);
                try{_sslEndPoint.close();}
                catch(IOException e2){
                    _logger.ignore(e2);}
            }
        }
    }

    return this;
}
 
Example 15
Source File: SSLSocketChannel2.java    From ans-android-sdk with GNU General Public License v3.0 4 votes vote down vote up
private boolean isHandShakeComplete() {
    HandshakeStatus status = sslEngine.getHandshakeStatus();
    return status == HandshakeStatus.FINISHED || status == HandshakeStatus.NOT_HANDSHAKING;
}
 
Example 16
Source File: SSLSocketChannel2.java    From Slyther with MIT License 4 votes vote down vote up
/**
 * This method will do whatever necessary to process the sslengine handshake.
 * Thats why it's called both from the {@link #read(ByteBuffer)} and {@link #write(ByteBuffer)}
 **/
private synchronized void processHandshake() throws IOException {
	if( sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING )
		return; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking.
	if( !tasks.isEmpty() ) {
		Iterator<Future<?>> it = tasks.iterator();
		while ( it.hasNext() ) {
			Future<?> f = it.next();
			if( f.isDone() ) {
				it.remove();
			} else {
				if( isBlocking() )
					consumeFutureUninterruptible( f );
				return;
			}
		}
	}

	if( sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP ) {
		if( !isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW ) {
			inCrypt.compact();
			int read = socketChannel.read( inCrypt );
			if( read == -1 ) {
				throw new IOException( "connection closed unexpectedly by peer" );
			}
			inCrypt.flip();
		}
		inData.compact();
		unwrap();
		if( readEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) {
			createBuffers( sslEngine.getSession() );
			return;
		}
	}
	consumeDelegatedTasks();
	if( tasks.isEmpty() || sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP ) {
		socketChannel.write( wrap( emptybuffer ) );
		if( writeEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) {
			createBuffers( sslEngine.getSession() );
			return;
		}
	}
	assert ( sslEngine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING );// this function could only leave NOT_HANDSHAKING after createBuffers was called unless #190 occurs which means that nio wrap/unwrap never return HandshakeStatus.FINISHED

	bufferallocations = 1; // look at variable declaration why this line exists and #190. Without this line buffers would not be be recreated when #190 AND a rehandshake occur.
}
 
Example 17
Source File: CapitalisingDummySslEngine.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
/**
 * Converts <-A-><-B-><-C-> to a_. <> is special and decodes as z_
 * Input such as "<A" will causes a {@link Status#BUFFER_UNDERFLOW} result status.
 */
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer dst)
        throws SSLException
{
    _unwrapCount++;

    if(_nextException != null)
    {
        throw _nextException;
    }

    Status resultStatus;
    final int consumed;
    final int produced;

    if (src.remaining() >= SHORT_ENCODED_CHUNK_SIZE)
    {
        src.mark();

        char begin = (char)src.get();
        char nextChar = (char)src.get(); // Could be - or >
        final int readSoFar = 2;
        final char capitalisedChar;

        if (nextChar != ENCODED_TEXT_END)
        {
            int remainingBytesForMaxLengthPacket = MAX_ENCODED_CHUNK_SIZE - readSoFar;
            if (src.remaining() < remainingBytesForMaxLengthPacket )
            {
                src.reset();
                resultStatus = Status.BUFFER_UNDERFLOW;
                return new SSLEngineResult(resultStatus, HandshakeStatus.NOT_HANDSHAKING, 0, 0);
            }
            else
            {
                char beginInner = nextChar;
                capitalisedChar = (char)src.get();
                char endInner = (char)src.get();
                char end = (char)src.get();
                consumed = MAX_ENCODED_CHUNK_SIZE;
                validateEncoded(begin, beginInner, capitalisedChar, endInner, end);
            }
        }
        else
        {
            assertEquals("Unexpected begin", Character.toString(ENCODED_TEXT_BEGIN), Character.toString(begin));
            capitalisedChar = 'Z';
            consumed = SHORT_ENCODED_CHUNK_SIZE;;
        }

        char lowerCaseChar = Character.toLowerCase(capitalisedChar);
        dst.put((byte)lowerCaseChar);
        dst.put((byte)CLEARTEXT_PADDING);
        produced = CLEAR_CHUNK_SIZE;

        resultStatus = Status.OK;
    }
    else
    {
        resultStatus = Status.BUFFER_UNDERFLOW;
        consumed = 0;
        produced = 0;
    }

    return new SSLEngineResult(resultStatus, HandshakeStatus.NOT_HANDSHAKING, consumed, produced);
}
 
Example 18
Source File: SSLSocketChannel2.java    From RipplePower with Apache License 2.0 4 votes vote down vote up
/**
 * This method will do whatever necessary to process the sslengine handshake.
 * Thats why it's called both from the {@link #read(ByteBuffer)} and {@link #write(ByteBuffer)}
 **/
private synchronized void processHandshake() throws IOException {
	if( sslEngine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING )
		return; // since this may be called either from a reading or a writing thread and because this method is synchronized it is necessary to double check if we are still handshaking.
	if( !tasks.isEmpty() ) {
		Iterator<Future<?>> it = tasks.iterator();
		while ( it.hasNext() ) {
			Future<?> f = it.next();
			if( f.isDone() ) {
				it.remove();
			} else {
				if( isBlocking() )
					consumeFutureUninterruptible( f );
				return;
			}
		}
	}

	if( sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP ) {
		if( !isBlocking() || readEngineResult.getStatus() == Status.BUFFER_UNDERFLOW ) {
			inCrypt.compact();
			int read = socketChannel.read( inCrypt );
			if( read == -1 ) {
				throw new IOException( "connection closed unexpectedly by peer" );
			}
			inCrypt.flip();
		}
		inData.compact();
		unwrap();
		if( readEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) {
			createBuffers( sslEngine.getSession() );
			return;
		}
	}
	consumeDelegatedTasks();
	if( tasks.isEmpty() || sslEngine.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_WRAP ) {
		socketChannel.write( wrap( emptybuffer ) );
		if( writeEngineResult.getHandshakeStatus() == HandshakeStatus.FINISHED ) {
			createBuffers( sslEngine.getSession() );
			return;
		}
	}
	assert ( sslEngine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING );// this function could only leave NOT_HANDSHAKING after createBuffers was called unless #190 occurs which means that nio wrap/unwrap never return HandshakeStatus.FINISHED

	bufferallocations = 1; // look at variable declaration why this line exists and #190. Without this line buffers would not be be recreated when #190 AND a rehandshake occur.
}
 
Example 19
Source File: SslConnection.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
public Connection handle() throws IOException
{
    try
    {
        allocateBuffers();

        boolean progress=true;

        while (progress)
        {
            progress=false;

            // If we are handshook let the delegate connection
            if (_engine.getHandshakeStatus()!=HandshakeStatus.NOT_HANDSHAKING)
                progress=process(null,null);

            // handle the delegate connection
            AsyncConnection next = (AsyncConnection)_connection.handle();
            if (next!=_connection && next!=null)
            {
                _connection=next;
                progress=true;
            }

            _logger.debug("{} handle {} progress={}", _session, this, progress);
        }
    }
    finally
    {
        releaseBuffers();

        if (!_ishut && _sslEndPoint.isInputShutdown() && _sslEndPoint.isOpen())
        {
            _ishut=true;
            try
            {
                _connection.onInputShutdown();
            }
            catch(Throwable x)
            {
                _logger.warn("onInputShutdown failed", x);
                try{_sslEndPoint.close();}
                catch(IOException e2){
                    _logger.ignore(e2);}
            }
        }
    }

    return this;
}
 
Example 20
Source File: SslConnection.java    From IoTgo_Android_App with MIT License 4 votes vote down vote up
public Connection handle() throws IOException
{
    try
    {
        allocateBuffers();

        boolean progress=true;

        while (progress)
        {
            progress=false;

            // If we are handshook let the delegate connection
            if (_engine.getHandshakeStatus()!=HandshakeStatus.NOT_HANDSHAKING)
                progress=process(null,null);

            // handle the delegate connection
            AsyncConnection next = (AsyncConnection)_connection.handle();
            if (next!=_connection && next!=null)
            {
                _connection=next;
                progress=true;
            }

            _logger.debug("{} handle {} progress={}", _session, this, progress);
        }
    }
    finally
    {
        releaseBuffers();

        if (!_ishut && _sslEndPoint.isInputShutdown() && _sslEndPoint.isOpen())
        {
            _ishut=true;
            try
            {
                _connection.onInputShutdown();
            }
            catch(Throwable x)
            {
                _logger.warn("onInputShutdown failed", x);
                try{_sslEndPoint.close();}
                catch(IOException e2){
                    _logger.ignore(e2);}
            }
        }
    }

    return this;
}