/*
@see com.ibm.wsspi.tcpchannel.SSLConnectionContext#renegotiate()
171966
public void renegotiate() {
        try {
            this.sslConnLink.getSSLEngine().beginHandshake();
        } catch (SSLException se) {
            FFDCFilter.processException(se,
                                        getClass().getName() + ".renegotiate", "1");
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Error while attempting handshake renegotiation; " + se);
            }
        }
    }
271436
@Override
    public boolean offer(final WaitStrategy.Offerable o) throws InterruptedException {
        double currentBackoff = backoffNanos;
        while (!o.offer()) {
            LockSupport.parkNanos((long) currentBackoff);
            currentBackoff = currentBackoff * coefficient;

        }
        return true;
    }
611170
public void handshake(NextFilter nextFilter) throws SSLException {
        for (;;) {
            switch (handshakeStatus) {
                case FINISHED :
                    session.setAttribute(
                            SslFilter.SSL_SESSION, sslEngine.getSession());
                    handshakeComplete = true;

                    if (logger.isDebugEnabled()) {
                        SSLSession sslSession = sslEngine.getSession();
                        logger.debug(String.format("SSL session ID %s on transport session #%d %s: cipher %s, app buffer size %d, packet buffer size %d", 
                            sslSession.getId(), session.getId(), session, sslSession.getCipherSuite(), sslSession.getApplicationBufferSize(), sslSession.getPacketBufferSize()));
                    }

                    if (!initialHandshakeComplete
                            && session.containsAttribute(SslFilter.USE_NOTIFICATION)) {
                        // SESSION_SECURED is fired only when it's the first handshake.
                        // (i.e. renegotiation shouldn't trigger SESSION_SECURED.)
                        initialHandshakeComplete = true;
                        scheduleMessageReceived(nextFilter,
                                SslFilter.SESSION_SECURED);
                    }
                    
                    return;
                    
                case NEED_TASK :
                    handshakeStatus = doTasks();
                    break;
                    
                case NEED_UNWRAP :
                    // we need more data read
                    SSLEngineResult.Status status = unwrapHandshake(nextFilter);
                    
                    if (status == SSLEngineResult.Status.BUFFER_UNDERFLOW &&
                            handshakeStatus != SSLEngineResult.HandshakeStatus.FINISHED ||
                            isInboundDone()) {
                        // We need more data or the session is closed
                        return;
                    }
                    
                    break;

                case NEED_WRAP :
                    // First make sure that the out buffer is completely empty. Since we
                    // cannot call wrap with data left on the buffer
                    if (outNetBuffer != null && outNetBuffer.hasRemaining()) {
                        return;
                    }

                    SSLEngineResult result;
                    createOutNetBuffer(0);
                    
                    for (;;) {
                        result = sslEngine.wrap(emptyBuffer.buf(), outNetBuffer.buf());
                        if (result.getStatus() == SSLEngineResult.Status.BUFFER_OVERFLOW) {
                            outNetBuffer.capacity(outNetBuffer.capacity() << 1, allocator);
                            outNetBuffer.limit(outNetBuffer.capacity());
                        } else {
                            break;
                        }
                    }

                    outNetBuffer.flip();
                    handshakeStatus = result.getHandshakeStatus();
                    writeNetBuffer(nextFilter);
                    break;
            
                default :
                    throw new IllegalStateException("Invalid Handshaking State"
                            + handshakeStatus);
            }
        }
    }
402374
@Override
    public void sessionEstablished(PayloadType pt, TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) throws NotConnectedException, InterruptedException {
        if (lc instanceof ICECandidate) {
            if (((ICECandidate) lc).getType().equals(Type.relay)) {
                RTPBridge rtpBridge = RTPBridge.relaySession(lc.getConnection(), lc.getSessionId(), lc.getPassword(), rc, lc);
            }
        }
    }
622993
protected void tryToRemoveAlpnNegotiator(ThirdPartyAlpnNegotiator negotiator, SSLEngine engine, SSLConnectionLink link) {
        // the Java 9 and IBM JSSE ALPN implementations don't use a negotiator object
        if (negotiator == null && isNativeAlpnActive()) {
            getNativeAlpnChoice(engine, link);
        } else if (negotiator == null && isIbmAlpnActive()) {
            getAndRemoveIbmAlpnChoice(engine, link);
        } else if (negotiator != null && isJettyAlpnActive() && negotiator instanceof JettyServerNegotiator) {
            ((JettyServerNegotiator) negotiator).removeEngine();
        } else if (negotiator != null && isGrizzlyAlpnActive() && negotiator instanceof GrizzlyAlpnNegotiator) {
            ((GrizzlyAlpnNegotiator) negotiator).removeServerNegotiatorEngine();
        }
    }
166469
private void onAcquire(final PooledConnection conn, String httpMethod, String uriStr, 
                           int attemptNum, CurrentPassport passport)
    {
        passport.setOnChannel(conn.getChannel());
        removeIdleStateHandler(conn);

        conn.setInUse();
        if (LOG.isDebugEnabled()) LOG.debug("PooledConnection acquired: " + conn.toString());
    }
1357942
public Future<Channel> renegotiate() {
        ChannelHandlerContext ctx = this.ctx;
        if (ctx == null) {
            throw new IllegalStateException();
        }

        return renegotiate(ctx.executor().<Channel>newPromise());
    }
1177377
private IQ receiveSessionInitiateAction(JingleSession session, Jingle inJingle) throws SmackException, InterruptedException {

        IQ response;
        boolean shouldAck = true;

        // According to XEP-166 when we get a session-initiate we need to check for:
        //      1. Initiator unknown
        //      2. Receiver redirection
        //      3. Does not support Jingle
        //      4. Does not support any <description> formats
        //      5. Does not support any <transport> formats
        // If all of the above are OK then we send an IQ type = result to ACK the session-initiate.

        // 1. Initiator unknown
        // TODO

        // 2. Receiver redirection
        // TODO

        // 3. Does not support Jingle
        // Handled by Smack's lower layer.

        // 4. Does not support any <description> formats
        // TODO

        // 5. Does not support any <transport> formats
        // TODO

        if (!shouldAck) {

            response = session.createJingleError(inJingle, JingleError.NEGOTIATION_ERROR);

        } else {

            // Create the Ack
            response = session.createAck(inJingle);

            session.setSessionState(JingleSessionStatePending.getInstance());

            // Now set up all of the initial content negotiators for the session.
            for (JingleContent jingleContent : inJingle.getContentsList()) {
                // First create the content negotiator for this <content> section.
                ContentNegotiator contentNeg = new ContentNegotiator(session, jingleContent.getCreator(), jingleContent
                        .getName());

                // Get the media negotiator that goes with the <description> of this content.
                JingleDescription jingleDescription = jingleContent.getDescription();

                // Loop through each media manager looking for the ones that matches the incoming
                // session-initiate <content> choices.
                // (Set the first media manager as the default, so that in case things don't match we can still negotiate.)
                JingleMediaManager chosenMediaManager = session.getMediaManagers().get(0);
                for (JingleMediaManager mediaManager : session.getMediaManagers()) {
                    boolean matches = true;
                    for (PayloadType mediaPayloadType : mediaManager.getPayloads()) {
                        for (PayloadType descPayloadType2 : jingleDescription.getPayloadTypesList()) {
                            if (mediaPayloadType.getId() != descPayloadType2.getId()) {
                                matches = false;
                            }
                        }
                        if (matches) {
                            chosenMediaManager = mediaManager;
                        }
                    }
                }

                // Create the media negotiator for this content description.
                contentNeg.setMediaNegotiator(new MediaNegotiator(session, chosenMediaManager, jingleDescription
                        .getPayloadTypesList(), contentNeg));

                // For each transport type in this content, try to find the corresponding transport manager.
                // Then create a transport negotiator for that transport.
                for (JingleTransport jingleTransport : jingleContent.getJingleTransportsList()) {
                    for (JingleMediaManager mediaManager : session.getMediaManagers()) {

                        JingleTransportManager transportManager = mediaManager.getTransportManager();
                        TransportResolver resolver = null;
                        try {
                            resolver = transportManager.getResolver(session);
                        } catch (XMPPException e) {
                            LOGGER.log(Level.WARNING, "exception", e);
                        }

                        if (resolver.getType().equals(TransportResolver.Type.rawupd)) {
                            contentNeg.setTransportNegotiator(new TransportNegotiator.RawUdp(session, resolver, contentNeg));
                        }
                        if (resolver.getType().equals(TransportResolver.Type.ice)) {
                            contentNeg.setTransportNegotiator(new TransportNegotiator.Ice(session, resolver, contentNeg));
                        }
                    }
                }

                // Add the content negotiator to the session.
                session.addContentNegotiator(contentNeg);
            }

            // Now setup to track the media negotiators, so that we know when (if) to send a session-accept.
            session.setupListeners();
        }

        return response;
    }
1095863
protected static io.grpc.netty.NegotiationType of(final NegotiationType negotiationType) {
        switch (negotiationType) {
            case PLAINTEXT:
                return io.grpc.netty.NegotiationType.PLAINTEXT;
            case PLAINTEXT_UPGRADE:
                return io.grpc.netty.NegotiationType.PLAINTEXT_UPGRADE;
            case TLS:
                return io.grpc.netty.NegotiationType.TLS;
            default:
                throw new IllegalArgumentException("Unsupported NegotiationType: " + negotiationType);
        }
    }
1224568
public long connectRenegotiate() {
        Lock readerLock = context.ctxLock.readLock();
        readerLock.lock();
        try {
            return SSLContext.sessionConnectRenegotiate(context.ctx);
        } finally {
            readerLock.unlock();
        }
    }
183038
private void validateNegotiation ( SmbTransportImpl trans, SmbSessionImpl sess ) throws CIFSException {
        if ( !trans.isSMB2() || sess.getCredentials().isAnonymous() || sess.getCredentials().isGuest()
                || !sess.getConfig().isRequireSecureNegotiate() ) {
            log.debug("Secure negotiation does not apply");
            return;
        }

        Smb2NegotiateResponse nego = (Smb2NegotiateResponse) trans.getNegotiateResponse();
        if ( nego.getSelectedDialect().atLeast(DialectVersion.SMB311) ) {
            // have preauth integrity instead
            log.debug("Secure negotiation does not apply, is SMB3.1");
            return;
        }
        Smb2NegotiateRequest negoReq = new Smb2NegotiateRequest(sess.getConfig(), trans.getRequestSecurityMode(nego));

        log.debug("Sending VALIDATE_NEGOTIATE_INFO");
        Smb2IoctlRequest req = new Smb2IoctlRequest(sess.getConfig(), Smb2IoctlRequest.FSCTL_VALIDATE_NEGOTIATE_INFO);
        req.setFlags(Smb2IoctlRequest.SMB2_O_IOCTL_IS_FSCTL);
        req.setInputData(
            new ValidateNegotiateInfoRequest(
                negoReq.getCapabilities(),
                negoReq.getClientGuid(),
                (short) negoReq.getSecurityMode(),
                negoReq.getDialects()));

        Smb2IoctlResponse resp;
        try {
            resp = send(req, RequestParam.NO_RETRY);
        }
        catch ( SMBSignatureValidationException e ) {
            throw new SMBProtocolDowngradeException("Signature error during negotiate validation", e);
        }
        catch ( SmbException e ) {
            if ( log.isDebugEnabled() ) {
                log.debug(String.format("VALIDATE_NEGOTIATE_INFO response code 0x%x", e.getNtStatus()));
            }
            log.trace("VALIDATE_NEGOTIATE_INFO returned error", e);
            if ( ( req.getResponse().isReceived() && req.getResponse().isVerifyFailed() ) || e.getNtStatus() == NtStatus.NT_STATUS_ACCESS_DENIED ) {
                // this is the signature error
                throw new SMBProtocolDowngradeException("Signature error during negotiate validation", e);
            }

            // other errors are treated as success
            return;
        }
        ValidateNegotiateInfoResponse out = resp.getOutputData(ValidateNegotiateInfoResponse.class);

        if ( nego.getSecurityMode() != out.getSecurityMode() || nego.getCapabilities() != out.getCapabilities()
                || nego.getDialectRevision() != out.getDialect() || !Arrays.equals(nego.getServerGuid(), out.getServerGuid()) ) {
            log.debug("Secure negotiation failure");
            throw new CIFSException("Mismatched attributes validating negotiate info");
        }

        log.debug("Secure negotiation OK");
    }
447770
public void rollback() throws HandlerException {
        if (_isInitiator) {
            try {
                _userTx.rollback();
            } catch (SystemException se) {
                throw CommonKnowledgeMessages.MESSAGES.userTransactionRollbackFailed(se);
            }
        } else if (_userTx != null) {
            try {
                _userTx.setRollbackOnly();
            } catch (SystemException se) {
                throw CommonKnowledgeMessages.MESSAGES.userTransactionSetRollbackOnlyFailed(se);
            }
        }
    }
536897
@Override
    public void sessionEstablished(PayloadType pt, TransportCandidate rc, TransportCandidate lc, JingleSession jingleSession) throws NotConnectedException, InterruptedException {
        RTPBridge rtpBridge = RTPBridge.relaySession(lc.getConnection(), lc.getSessionId(), lc.getPassword(), rc, lc);
    }
840060
private void reconnect(WebSocketChannel channel, WSURI uri, String protocol) {
        LOG.entering(CLASS_NAME, "reconnect", new Object[] { uri, protocol });

        WebSocketNativeChannel wsChannel = (WebSocketNativeChannel)channel;
        wsChannel.redirectUri = uri;
        
        WebSocketCompositeChannel compChannel = (WebSocketCompositeChannel)channel.getParent();
        HttpRedirectPolicy option = compChannel.getFollowRedirect();
        URI currentURI = channel.getLocation().getURI();
        URI redirectURI = uri.getURI();
        
        // option will be null only for unit tests.
        if ((option != null) && (option.compare(currentURI, redirectURI) != 0)) {
            String s = String.format("%s: Cannot redirect from '%s' to '%s'",
                                     option, currentURI, redirectURI);
            channel.preventFallback = true;
            throw new IllegalStateException(s);
        }
        
        wsChannel.reconnecting.compareAndSet(false, true);
    }
415837
private synchronized void connectionOpened(String protocol, 
                                               String extensionsHeader) {
        // ### TODO: Currently, the Gateway is not sending the negotiated
        //           protocol.
        setNegotiatedProtocol(protocol);
        
        // Parse the negotiated extensions and parameters. This can result in 
        // _exception to be setup indicating that there is something wrong
        // while parsing the negotiated extensions and parameters.
        setNegotiatedExtensions(extensionsHeader);
        
        if ((getException() == null) && (_readyState == ReadyState.CONNECTING)) {
            _readyState = ReadyState.OPEN;
        }
        else {
            // The exception can be caused either while parsing the negotiated
            // extensions and parameters or the expiry of the connection timeout.
            // The parsing of negotiated extension can cause an exception if -- 
            // 1) a negotiated extension is not an enabled extension or
            // 2) the type of a negotiated parameter is not String.
            _readyState = ReadyState.CLOSED;
            
            // Inform the Gateway to close the WebSocket.
            _handler.processClose(_channel, 0, null);
        }

        // Unblock the connect() call so that it can proceed.
        notifyAll();
    }
1223267
public static ProtocolNegotiator httpProxy(final SocketAddress proxyAddress,
      final @Nullable String proxyUsername, final @Nullable String proxyPassword,
      final ProtocolNegotiator negotiator) {
    final AsciiString scheme = negotiator.scheme();
    Preconditions.checkNotNull(proxyAddress, "proxyAddress");
    Preconditions.checkNotNull(negotiator, "negotiator");
    class ProxyNegotiator implements ProtocolNegotiator {
      @Override
      public ChannelHandler newHandler(GrpcHttp2ConnectionHandler http2Handler) {
        HttpProxyHandler proxyHandler;
        if (proxyUsername == null || proxyPassword == null) {
          proxyHandler = new HttpProxyHandler(proxyAddress);
        } else {
          proxyHandler = new HttpProxyHandler(proxyAddress, proxyUsername, proxyPassword);
        }
        return new BufferUntilProxyTunnelledHandler(
            proxyHandler, negotiator.newHandler(http2Handler));
      }

      @Override
      public AsciiString scheme() {
        return scheme;
      }

      // This method is not normally called, because we use httpProxy on a per-connection basis in
      // NettyChannelBuilder. Instead, we expect `negotiator' to be closed by NettyTransportFactory.
      @Override
      public void close() {
        negotiator.close();
      }
    }

    return new ProxyNegotiator();
  }
722415
static void rcvRollbackTransaction(CommsByteBuffer request, Conversation conversation,
                                      int requestNumber, boolean allocatedFromBufferPool,
                                      boolean partOfExchange)
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "rcvRollbackTransaction",
                                           new Object[]
                                           {
                                              request,
                                              conversation,
                                              ""+requestNumber,
                                              ""+allocatedFromBufferPool
                                            });

      short connectionObjectId = request.getShort();  // BIT16 ConnectionObjectId
      int clientTransactionId = request.getInt();     // BIT32 Client transaction Id

      if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
      {
         SibTr.debug(tc, "SICoreConnection Id:", connectionObjectId);
         SibTr.debug(tc, "Client transaction Id:", clientTransactionId);
      }

      try
      {
         // Get the transaction out of the table
         ServerLinkLevelState linkState = (ServerLinkLevelState) conversation.getLinkLevelAttachment();
         SITransaction tran = linkState.getTransactionTable().get(clientTransactionId);

         if (tran == IdToTransactionTable.INVALID_TRANSACTION)
         {
            Throwable e = linkState.getTransactionTable().getExceptionForRollbackOnlyLocalTransaction(clientTransactionId);

            //Remove transaction from the table
            linkState.getTransactionTable().removeLocalTransaction(clientTransactionId);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Looks like the transaction failed to create", e);
         }
         else
         {
            // At this point here the transaction will only be rolled back.
            // Therefore, any subsequent operations will be invalid and will be thrown out
            // by the client. As such, remove it from the table.
            linkState.getTransactionTable().removeLocalTransaction(clientTransactionId);

            SIUncoordinatedTransaction siTran = (SIUncoordinatedTransaction)tran;
            siTran.rollback();
         }

         try
         {
            conversation.send(poolManager.allocate(),
                              JFapChannelConstants.SEG_ROLLBACK_TRANSACTION_R,
                              requestNumber,
                              JFapChannelConstants.PRIORITY_MEDIUM,
                              true,
                              ThrottlingPolicy.BLOCK_THREAD,
                              null);
         }
         catch (SIException e)
         {
            FFDCFilter.processException(e,
                                        CLASS_NAME + ".rcvRollbackTransaction",
                                        CommsConstants.STATICCATTRANSACTION_ROLLBACK_01);

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, e.getMessage(), e);

            SibTr.error(tc, "COMMUNICATION_ERROR_SICO2026", e);
         }
      }
      catch (SIException e)
      {
         //No FFDC code needed
         //Only FFDC if we haven't received a meTerminated event.
         if(!((ConversationState)conversation.getAttachment()).hasMETerminated())
         {
            FFDCFilter.processException(e,
                                       CLASS_NAME + ".rcvRollbackTransaction",
                                       CommsConstants.STATICCATTRANSACTION_ROLLBACK_02);
         }

         if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, e.getMessage(), e);

         StaticCATHelper.sendExceptionToClient(e,
                                               CommsConstants.STATICCATTRANSACTION_ROLLBACK_02,
                                               conversation, requestNumber);
      }

      request.release(allocatedFromBufferPool);

      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "rcvRollbackTransaction");
   }