Java Code Examples for javax.net.ssl.SSLEngineResult.Status#CLOSED

The following examples show how to use javax.net.ssl.SSLEngineResult.Status#CLOSED . 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
@Override
public int write(ByteBuffer src) throws IOException {
    if (!isHandShakeComplete()) {
        processHandshake();
        return 0;
    }
    // assert ( bufferallocations > 1 ); //see #190
    //if( bufferallocations <= 1 ) {
    //	createBuffers( sslEngine.getSession() );
    //}
    int num = socketChannel.write(wrap(src));
    if (writeEngineResult.getStatus() == Status.CLOSED) {
        throw new EOFException("Connection is closed");
    }
    return num;
}
 
Example 2
Source File: SSLSocketChannel2.java    From ans-android-sdk with GNU General Public License v3.0 6 votes vote down vote up
/**
 * {@link #read(ByteBuffer)} may not be to leave all buffers(inData, inCrypt)
 **/
private int readRemaining(ByteBuffer dst) throws SSLException {
    if (inData.hasRemaining()) {
        return transfereTo(inData, dst);
    }
    if (!inData.hasRemaining()) {
        inData.clear();
    }
    // test if some bytes left from last read (e.g. BUFFER_UNDERFLOW)
    if (inCrypt.hasRemaining()) {
        unwrap();
        int amount = transfereTo(inData, dst);
        if (readEngineResult.getStatus() == Status.CLOSED) {
            return -1;
        }
        if (amount > 0) {
            return amount;
        }
    }
    return 0;
}
 
Example 3
Source File: SslHandler.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Start SSL shutdown process.
 *
 * @return <tt>true</tt> if shutdown process is started.
 *         <tt>false</tt> if shutdown process is already finished.
 * @throws SSLException on errors
 */
boolean closeOutbound() throws SSLException {
	if (sslEngine == null || sslEngine.isOutboundDone())
		return false;

	sslEngine.closeOutbound();

	createOutNetBuffer(0);

	for (;;) {
		SSLEngineResult result = sslEngine.wrap(SimpleBufferAllocator.emptyBuffer.buf(), outNetBuffer.buf());
		if (result.getStatus() != Status.BUFFER_OVERFLOW) {
			if (result.getStatus() != Status.CLOSED)
				throw new SSLException("improper close state: " + result);
			break;
		}
		outNetBuffer = IoBuffer.reallocate(outNetBuffer, outNetBuffer.capacity() << 1);
		outNetBuffer.limit(outNetBuffer.capacity());
	}

	outNetBuffer.flip();

	return true;
}
 
Example 4
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
void doClosure() throws IOException {
   try {
      this.handshaking.lock();
      ByteBuffer tmp = this.allocate(SSLStreams.BufType.APPLICATION);

      SSLStreams.WrapperResult r;
      do {
         tmp.clear();
         tmp.flip();
         r = this.wrapper.wrapAndSendX(tmp, true);
      } while(r.result.getStatus() != Status.CLOSED);
   } finally {
      this.handshaking.unlock();
   }

}
 
Example 5
Source File: SSLDelegate.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * send the data in the given ByteBuffer. If a handshake is needed
 * then this is handled within this method. When this call returns,
 * all of the given user data has been sent and any handshake has been
 * completed. Caller should check if engine has been closed.
 */
WrapperResult sendData (ByteBuffer[] src, int offset, int len) throws IOException {
    WrapperResult r = WrapperResult.createOK();
    while (countBytes(src, offset, len) > 0) {
        r = wrapper.wrapAndSend(src, offset, len, false);
        Status status = r.result.getStatus();
        if (status == Status.CLOSED) {
            doClosure ();
            return r;
        }
        HandshakeStatus hs_status = r.result.getHandshakeStatus();
        if (hs_status != HandshakeStatus.FINISHED &&
            hs_status != HandshakeStatus.NOT_HANDSHAKING)
        {
            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: 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 9
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public void write(byte[] b, int off, int len) throws IOException {
   if (this.closed) {
      throw new IOException("output stream is closed");
   } else {
      while(len > 0) {
         int l = len > this.buf.capacity() ? this.buf.capacity() : len;
         this.buf.clear();
         this.buf.put(b, off, l);
         len -= l;
         off += l;
         this.buf.flip();
         SSLStreams.WrapperResult r = SSLStreams.this.sendData(this.buf);
         if (r.result.getStatus() == Status.CLOSED) {
            this.closed = true;
            if (len > 0) {
               throw new IOException("output stream is closed");
            }
         }
      }

   }
}
 
Example 10
Source File: SSLTunnelConnection.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
long write(ByteBuffer buffer) throws IOException {
    //debugPrint("Send", buffer);
    long l = buffer.remaining();
    WrapperResult r = sslDelegate.sendData(buffer);
    if (r.result.getStatus() == Status.CLOSED) {
        if (l > 0) {
            throw new IOException("SSLHttpConnection closed");
        }
    }
    return l;
}
 
Example 11
Source File: SSLTunnelConnection.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
long write(ByteBuffer[] buffers, int start, int number) throws IOException {
    //debugPrint("Send", buffers, start, number);
    long l = countBytes(buffers, start, number);
    WrapperResult r = sslDelegate.sendData(buffers, start, number);
    if (r.result.getStatus() == Status.CLOSED) {
        if (l > 0) {
            throw new IOException("SSLHttpConnection closed");
        }
    }
    return l;
}
 
Example 12
Source File: SqueakSSL.java    From trufflesqueak with MIT License 5 votes vote down vote up
private static void decryptOne(final SqSSL ssl, final ByteBuffer target) throws SSLException {
    ssl.buffer.flip();
    final SSLEngineResult result = unwrap(ssl, ssl.buffer, target);
    checkStatus("Decrypt status", result, Status.OK, Status.BUFFER_UNDERFLOW, Status.CLOSED);

    if (result.getStatus() == Status.OK || result.getStatus() == Status.BUFFER_UNDERFLOW) {
        ssl.buffer.compact();
    }

    if (result.getStatus() == Status.CLOSED) {
        connectionClosed(ssl);
    }
}
 
Example 13
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 14
Source File: SslReadWriteSelectorHandler.java    From simplewebserver with Apache License 2.0 5 votes vote down vote up
/**
 * Begin the shutdown process.
 * <p>
 * Close out the SSLEngine if not already done so, then
 * wrap our outgoing close_notify message and try to send it on.
 * <p>
 * Return true when we're done passing the shutdown messsages.
 */
private boolean shutdown() throws IOException {

    if (!shutdown) {
        sslEngine.closeOutbound();
        shutdown = true;
    }

    if (outNetBB.hasRemaining() && tryFlush(outNetBB)) {
        return false;
    }

    /*
     * By RFC 2616, we can "fire and forget" our close_notify
     * message, so that's what we'll do here.
     */
    outNetBB.clear();
    SSLEngineResult result = sslEngine.wrap(hsBB, outNetBB);
    if (result.getStatus() != Status.CLOSED) {
        throw new SSLException("Improper close state");
    }
    outNetBB.flip();

    /*
     * We won't wait for a select here, but if this doesn't work,
     * we'll cycle back through on the next select.
     */
    if (outNetBB.hasRemaining()) {
        tryFlush(outNetBB);
    }

    return (!outNetBB.hasRemaining() &&
            (result.getHandshakeStatus() != HandshakeStatus.NEED_WRAP));
}
 
Example 15
Source File: SSLConnection.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
long write(ByteBuffer[] buffers, int start, int number) throws IOException {
    //debugPrint("Send", buffers, start, number);
    long l = countBytes(buffers, start, number);
    WrapperResult r = sslDelegate.sendData(buffers, start, number);
    if (r.result.getStatus() == Status.CLOSED) {
        if (l > 0) {
            throw new IOException("SSLHttpConnection closed");
        }
    }
    return l;
}
 
Example 16
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
SSLStreams.WrapperResult recvAndUnwrap(ByteBuffer dst) throws IOException {
   Status status = Status.OK;
   SSLStreams.WrapperResult r = SSLStreams.this.new WrapperResult();
   r.buf = dst;
   if (this.closed) {
      throw new IOException("Engine is closed");
   } else {
      boolean needData;
      if (this.u_remaining > 0) {
         this.unwrap_src.compact();
         this.unwrap_src.flip();
         needData = false;
      } else {
         this.unwrap_src.clear();
         needData = true;
      }

      Object var5 = this.unwrapLock;
      synchronized(this.unwrapLock) {
         do {
            if (needData) {
               int x;
               do {
                  x = this.chan.read(this.unwrap_src);
               } while(x == 0);

               if (x == -1) {
                  throw new IOException("connection closed for reading");
               }

               this.unwrap_src.flip();
            }

            r.result = this.engine.unwrap(this.unwrap_src, r.buf);
            status = r.result.getStatus();
            if (status == Status.BUFFER_UNDERFLOW) {
               if (this.unwrap_src.limit() == this.unwrap_src.capacity()) {
                  this.unwrap_src = SSLStreams.this.realloc(this.unwrap_src, false, SSLStreams.BufType.PACKET);
               } else {
                  this.unwrap_src.position(this.unwrap_src.limit());
                  this.unwrap_src.limit(this.unwrap_src.capacity());
               }

               needData = true;
            } else if (status == Status.BUFFER_OVERFLOW) {
               r.buf = SSLStreams.this.realloc(r.buf, true, SSLStreams.BufType.APPLICATION);
               needData = false;
            } else if (status == Status.CLOSED) {
               this.closed = true;
               r.buf.flip();
               return r;
            }
         } while(status != Status.OK);
      }

      this.u_remaining = this.unwrap_src.remaining();
      return r;
   }
}
 
Example 17
Source File: SSLSocketChannel2.java    From clevertap-android-sdk with MIT License 4 votes vote down vote up
@Override
public boolean isNeedRead() {
    return inData.hasRemaining() || ( inCrypt.hasRemaining() && readEngineResult.getStatus() != Status.BUFFER_UNDERFLOW && readEngineResult.getStatus() != Status.CLOSED );
}
 
Example 18
Source File: SSLStreams.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
SSLStreams.WrapperResult recvAndUnwrap(ByteBuffer dst) throws IOException {
   Status status = Status.OK;
   SSLStreams.WrapperResult r = SSLStreams.this.new WrapperResult();
   r.buf = dst;
   if (this.closed) {
      throw new IOException("Engine is closed");
   } else {
      boolean needData;
      if (this.u_remaining > 0) {
         this.unwrap_src.compact();
         this.unwrap_src.flip();
         needData = false;
      } else {
         this.unwrap_src.clear();
         needData = true;
      }

      Object var5 = this.unwrapLock;
      synchronized(this.unwrapLock) {
         do {
            if (needData) {
               int x;
               do {
                  x = this.chan.read(this.unwrap_src);
               } while(x == 0);

               if (x == -1) {
                  throw new IOException("connection closed for reading");
               }

               this.unwrap_src.flip();
            }

            r.result = this.engine.unwrap(this.unwrap_src, r.buf);
            status = r.result.getStatus();
            if (status == Status.BUFFER_UNDERFLOW) {
               if (this.unwrap_src.limit() == this.unwrap_src.capacity()) {
                  this.unwrap_src = SSLStreams.this.realloc(this.unwrap_src, false, SSLStreams.BufType.PACKET);
               } else {
                  this.unwrap_src.position(this.unwrap_src.limit());
                  this.unwrap_src.limit(this.unwrap_src.capacity());
               }

               needData = true;
            } else if (status == Status.BUFFER_OVERFLOW) {
               r.buf = SSLStreams.this.realloc(r.buf, true, SSLStreams.BufType.APPLICATION);
               needData = false;
            } else if (status == Status.CLOSED) {
               this.closed = true;
               r.buf.flip();
               return r;
            }
         } while(status != Status.OK);
      }

      this.u_remaining = this.unwrap_src.remaining();
      return r;
   }
}
 
Example 19
Source File: SSLSocketChannel.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
public synchronized int read(ByteBuffer dst) throws IOException
{
    if (socketChannel.socket().isInputShutdown())
    {
        throw new ClosedChannelException();
    }
    else if (initialized != 0)
    {
        handshake(SelectionKey.OP_READ);
        
        return 0;
    }
    else if (shutdown)
    {
        shutdown();
        return 0;
    }
    else if (sslEngine.isInboundDone())
    {
        return -1;
    }
    else if ((fill(inputBuffer[0]) < 0) && (inputBuffer[0].position() == 0))
    {
        return -1;
    }

    SSLEngineResult result;
    Status status;
    do
    {
        if (!prepare(inputCache, minCacheSize))
        {
            // Overflow!
            break;
        }

        inputBuffer[0].flip();
        try
        {
            result = sslEngine.unwrap(inputBuffer[0], inputCache[0]);
        }
        finally
        {
            inputBuffer[0].compact();
            inputCache[0].flip();
        }

        status = result.getStatus();
        if ((status == Status.OK) || (status == Status.BUFFER_UNDERFLOW))
        {
            if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK)
            {
                runTasks();
            }
        }
        else
        {
            if (status == Status.CLOSED)
            {
                shutdown();
            }

            throw new IOException("Read error '" + result.getStatus()
                + '\'');
        }
    } while ((inputBuffer[0].position() != 0)
        && (status != Status.BUFFER_UNDERFLOW));

    int n = inputCache[0].remaining();
    if (n > 0)
    {
        if (n > dst.remaining())
        {
            n = dst.remaining();
        }
        for (int i = 0; i < n; i++)
        {
            dst.put(inputCache[0].get());
        }
    }
    return n;
}
 
Example 20
Source File: SSLSocketChannel.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void close() throws IOException {
    logger.debug("{} Closing Connection", this);
    if (channel == null) {
        return;
    }

    if (closed) {
        return;
    }

    try {
        engine.closeOutbound();

        final byte[] emptyMessage = new byte[0];

        final ByteBuffer appDataOut = ByteBuffer.wrap(emptyMessage);
        final ByteBuffer outboundBuffer = streamOutManager.prepareForWrite(engine.getSession().getApplicationBufferSize());
        final SSLEngineResult handshakeResult = engine.wrap(appDataOut, outboundBuffer);

        if (handshakeResult.getStatus() != Status.CLOSED) {
            throw new IOException("Invalid close state - will not send network data");
        }

        final ByteBuffer readableStreamOut = streamOutManager.prepareForRead(1);
        writeFully(readableStreamOut);
    } finally {
        // Drain the incoming TCP buffer
        final ByteBuffer discardBuffer = ByteBuffer.allocate(8192);
        try {
            int bytesDiscarded = channel.read(discardBuffer);
            while (bytesDiscarded > 0) {
                discardBuffer.clear();
                bytesDiscarded = channel.read(discardBuffer);
            }
        } catch (Exception e) {
        }

        closeQuietly(channel.socket());
        closeQuietly(channel);
        closed = true;
    }
}