Sets the start server fields for the passed handshake request.
337633
private void setStartServerFields(HandshakerReq.Builder req, ByteBuffer inBytes) {
    ServerHandshakeParameters serverParameters =
        ServerHandshakeParameters.newBuilder().addRecordProtocols(RECORD_PROTOCOL).build();
    StartServerHandshakeReq.Builder startServerReq =
        StartServerHandshakeReq.newBuilder()
            .addApplicationProtocols(APPLICATION_PROTOCOL)
            .putHandshakeParameters(HandshakeProtocol.ALTS.getNumber(), serverParameters)
            .setInBytes(ByteString.copyFrom(inBytes.duplicate()));
    if (handshakerOptions.getRpcProtocolVersions() != null) {
      startServerReq.setRpcVersions(handshakerOptions.getRpcProtocolVersions());
    }
    req.setServerStart(startServerReq);
  }
551098
synchronized public void setWantClientAuth(boolean flag) {
        doClientAuth = (flag ?
            SSLEngineImpl.clauth_requested : SSLEngineImpl.clauth_none);

        if ((handshaker != null) &&
                (handshaker instanceof ServerHandshaker) &&
                !handshaker.activated()) {
            ((ServerHandshaker) handshaker).setClientAuth(doClientAuth);
        }
    }
985139
protected void readyInboundPostHandshake(
                                             WsByteBuffer netBuffer,
                                             WsByteBuffer decryptedNetBuffer,
                                             WsByteBuffer encryptedAppBuffer,
                                             HandshakeStatus hsStatus) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "readyInboundPostHandshake, vc=" + getVCHash());
        }

        // Release the no longer needed buffers.
        encryptedAppBuffer.release();

        if (hsStatus == HandshakeStatus.FINISHED) {
            AlpnSupportUtils.getAlpnResult(getSSLEngine(), this);

            // PK16095 - take certain actions when the handshake completes
            getChannel().onHandshakeFinish(getSSLEngine());

            // Handshake complete. Now get the request. Use our read interface so unwrap already done.
            // Check if data exists in the network buffer still. This would be app data beyond handshake.
            if (netBuffer.remaining() == 0 || netBuffer.position() == 0) {
                // No app data. Release the netBuffer as it will no longer be used.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Releasing netBuffer: " + netBuffer.hashCode());
                }
                netBuffer.release();
                getDeviceReadInterface().setBuffers(null);
            } else {
                // Found encrypted app data. Don't release the network buffer yet. Let the read decrypt it.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "App data exists in netBuffer after handshake: " + netBuffer.remaining());
                }
            }

            readInterface.setBuffer(decryptedNetBuffer);
            // No need to save number of bytes read.
            MyReadCompletedCallback readCallback = new MyReadCompletedCallback(decryptedNetBuffer);
            if (null != readInterface.read(1, readCallback, false, TCPRequestContext.USE_CHANNEL_TIMEOUT)) {
                // Read was handled synchronously.
                determineNextChannel();
            }
        } else {
            // Unknown result from handshake. All other results should have thrown exceptions.
            // Clean up buffers used during read.
            netBuffer.release();
            getDeviceReadInterface().setBuffers(null);
            decryptedNetBuffer.release();
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Unhandled result from SSL engine: " + hsStatus);
            }
            SSLException ssle = new SSLException("Unhandled result from SSL engine: " + hsStatus);
            FFDCFilter.processException(ssle, getClass().getName(), "401", this);
            close(getVirtualConnection(), ssle);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "readyInboundPostHandshake");
        }
    }
514559
function Endpoint(log, role, settings, filters) {
  Duplex.call(this);

  // * Initializing logging infrastructure
  this._log = log.child({ component: 'endpoint', e: this });

  // * First part of the handshake process: sending and receiving the client connection header
  //   prelude.
  assert((role === 'CLIENT') || role === 'SERVER');
  if (role === 'CLIENT') {
    this._writePrelude();
  } else {
    this._readPrelude();
  }

  // * Initialization of component. This includes the second part of the handshake process:
  //   sending the first SETTINGS frame. This is done by the connection class right after
  //   initialization.
  this._initializeDataFlow(role, settings, filters || {});

  // * Initialization of management code.
  this._initializeManagement();

  // * Initializing error handling.
  this._initializeErrorHandling();
}
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);
            }
        }
    }
76203
public void bindAndStart(int port) throws Exception {
        server = new NioServer(new StreamConnectionFactory() {
            @Override
            public ProtobufConnection<Protos.TwoWayChannelMessage> getNewConnection(InetAddress inetAddress, int port) {
                return new ServerHandler(new InetSocketAddress(inetAddress, port), timeoutSeconds).socketProtobufHandler;
            }
        }, new InetSocketAddress(port));
        server.startAsync();
        server.awaitRunning();
    }
1053859
public void serverCallStarted(ServerCallInfo<?, ?> callInfo) {
    for (StreamTracer tracer : tracers) {
      ((ServerStreamTracer) tracer).serverCallStarted(callInfo);
    }
  }
642798
public synchronized void init() {
		for (SocketBinding binding : socketBindings) {
			socketBindingsMap.put(binding.getName(), binding);
		}
		for (SecurityRealm realm : securityRealms) {
			securityRealmsMap.put(realm.getName(), realm);
		}
		for (Interface iface : interfaces) {
			interfacesMap.put(iface.getName(), iface);
		}
		if (subsystem != null) {
			for (UndertowSubsystem.FileHandler handler : subsystem.getFileHandlers()) {
				handlersMap.put(handler.getName(), handler);
			}
			if (subsystem.getFilters() != null) {
				for (UndertowSubsystem.ResponseHeaderFilter filter : subsystem.getFilters().getResponseHeaders()) {
					filtersMap.put(filter.getName(), filter);
				}
				for (UndertowSubsystem.ErrorPageFilter filter : subsystem.getFilters().getErrorPages()) {
					filtersMap.put(filter.getName(), filter);
				}
				for (UndertowSubsystem.CustomFilter filter : subsystem.getFilters().getCustomFilters()) {
					filtersMap.put(filter.getName(), filter);
				}
			}
		}
	}
542060
void start(Handler<ConnectionOutputBatch> startHandler) {
    connection.doBatchStart(id, args);
    this.startHandler = startHandler;
  }
1032785
def start(request_params)
      # close the previous if exists
      finish
      # create new connection
      @server         = request_params[:server]
      @port           = request_params[:port]
      @protocol       = request_params[:protocol]
      @proxy_host     = request_params[:proxy_host]
      @proxy_port     = request_params[:proxy_port]
      @proxy_username = request_params[:proxy_username]
      @proxy_password = request_params[:proxy_password]
      
      SECURITY_PARAMS.each do |param_name|
        @params[param_name] = request_params[param_name]
      end

      @logger.info("Opening new #{@protocol.upcase} connection to #@server:#@port")

      @logger.info("Connecting to proxy #{@proxy_host}:#{@proxy_port} with username" +
                   " #{@proxy_username.inspect}") unless @proxy_host.nil?

      @http = Net::HTTP.new(@server, @port, @proxy_host, @proxy_port, @proxy_username,
                            @proxy_password)
      @http.open_timeout = get_param(:http_connection_open_timeout, request_params)
      @http.read_timeout = get_param(:http_connection_read_timeout, request_params)

      if @protocol == 'https'
        verifyCallbackProc = Proc.new{ |ok, x509_store_ctx|
          # List of error codes: http://www.openssl.org/docs/apps/verify.html
          code = x509_store_ctx.error
          msg = x509_store_ctx.error_string
          if request_params[:fail_if_ca_mismatch] && code != 0
            false
          else
            true
          end
        }
        @http.use_ssl = true

        ca_file = get_param(:ca_file)
        if ca_file && File.exists?(ca_file)
          # Documentation for 'http.rb':
          # : verify_mode, verify_mode=((|mode|))
          #    Sets the flags for server the certification verification at
          #    beginning of SSL/TLS session.
          #    OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable.
          #
          # KHRVI: looks like the constant VERIFY_FAIL_IF_NO_PEER_CERT is not acceptable
          @http.verify_callback = verifyCallbackProc
          @http.ca_file= ca_file
          @http.verify_mode = get_param(:use_server_auth) ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE
          # The depth count is 'level 0:peer certificate', 'level 1: CA certificate', 'level 2: higher level CA certificate', and so on.
          # Setting the maximum depth to 2 allows the levels 0, 1, and 2. The default depth limit is 9, allowing for the peer certificate and additional 9 CA certificates.
          @http.verify_depth    = 9
        else
          @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end
        
        # CERT
        cert_file = get_param(:cert_file, request_params)
        cert      = File.read(cert_file) if cert_file && File.exists?(cert_file)
        cert    ||= get_param(:cert, request_params)
        # KEY
        key_file  = get_param(:key_file,  request_params)
        key       = File.read(key_file) if key_file && File.exists?(key_file)
        key     ||= get_param(:key,  request_params)
        if cert && key
          begin
            @http.verify_callback = verifyCallbackProc
            @http.cert = OpenSSL::X509::Certificate.new(cert)
            @http.key  = OpenSSL::PKey::RSA.new(key)
          rescue OpenSSL::PKey::RSAError, OpenSSL::X509::CertificateError => e
            @logger.error "##### Error loading SSL client cert or key: #{e.message} :: backtrace #{e.backtrace}"
            raise e
          end
        end
      end
      # open connection
      @http.start
    end
1104141
@Override
	public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
		sec.getUserProperties().put(Constants.HANDSHAKEREQUEST, request);
		super.modifyHandshake(sec, request, response);
	}
522349
private void handshake() {
        if (engine.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) {
            // Not all SSLEngine implementations support calling beginHandshake multiple times while a handshake
            // is in progress. See https://github.com/netty/netty/issues/4718.
            return;
        } else {
            if (handshakePromise.isDone()) {
                // If the handshake is done already lets just return directly as there is no need to trigger it again.
                // This can happen if the handshake(...) was triggered before we called channelActive(...) by a
                // flush() that was triggered by a ChannelFutureListener that was added to the ChannelFuture returned
                // from the connect(...) method. In this case we will see the flush() happen before we had a chance to
                // call fireChannelActive() on the pipeline.
                return;
            }
        }

        // Begin handshake.
        final ChannelHandlerContext ctx = this.ctx;
        try {
            engine.beginHandshake();
            wrapNonAppData(ctx, false);
        } catch (Throwable e) {
            setHandshakeFailure(ctx, e);
        } finally {
            forceFlush(ctx);
        }
    }
1095580
@Reference(policy = ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.OPTIONAL)
    protected synchronized void setServerStarted(ServerStarted serverStarted) {
        isServerStarted = true;

        // Start SystemModule if everything else is ready
        startManagementEJB();
    }
780842
public void setResources(java.util.Collection<HandshakeResource> resources) {
        if (resources == null) {
            this.resources = null;
            return;
        }

        this.resources = new java.util.ArrayList<HandshakeResource>(resources);
    }
308180
public void setHandshakeType(byte handshakeType) {
        if (log.isTraceEnabled()) {
            if (handshakeType < HANDSHAKE_TYPES.length) {
                log.trace("Setting handshake type: {}", HANDSHAKE_TYPES[handshakeType]);
            } else {
                log.trace("Invalid handshake type: {}", handshakeType);
            }
        }
        this.handshakeType = handshakeType;
    }
1017511
@Handler
    public void onStart(Start event) throws IOException {
        closing = false;
        serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(serverAddress, backlog);
        MBeanView.addServer(this);
        fire(new NioRegistration(this, serverSocketChannel,
            SelectionKey.OP_ACCEPT, this), Channel.BROADCAST);
    }
1165125
async def handler(self) -> None:
        
        try:

            try:
                path = await self.handshake(
                    origins=self.origins,
                    available_extensions=self.available_extensions,
                    available_subprotocols=self.available_subprotocols,
                    extra_headers=self.extra_headers,
                )
            except ConnectionError:
                logger.debug("Connection error in opening handshake", exc_info=True)
                raise
            except Exception as exc:
                if isinstance(exc, AbortHandshake):
                    status, headers, body = exc.status, exc.headers, exc.body
                elif isinstance(exc, InvalidOrigin):
                    logger.debug("Invalid origin", exc_info=True)
                    status, headers, body = (
                        http.HTTPStatus.FORBIDDEN,
                        Headers(),
                        (str(exc) + "\n").encode(),
                    )
                elif isinstance(exc, InvalidUpgrade):
                    logger.debug("Invalid upgrade", exc_info=True)
                    status, headers, body = (
                        http.HTTPStatus.UPGRADE_REQUIRED,
                        Headers([("Upgrade", "websocket")]),
                        (str(exc) + "\n").encode(),
                    )
                elif isinstance(exc, InvalidHandshake):
                    logger.debug("Invalid handshake", exc_info=True)
                    status, headers, body = (
                        http.HTTPStatus.BAD_REQUEST,
                        Headers(),
                        (str(exc) + "\n").encode(),
                    )
                else:
                    logger.warning("Error in opening handshake", exc_info=True)
                    status, headers, body = (
                        http.HTTPStatus.INTERNAL_SERVER_ERROR,
                        Headers(),
                        b"See server log for more information.\n",
                    )

                headers.setdefault("Date", email.utils.formatdate(usegmt=True))
                headers.setdefault("Server", USER_AGENT)
                headers.setdefault("Content-Length", str(len(body)))
                headers.setdefault("Content-Type", "text/plain")
                headers.setdefault("Connection", "close")

                self.write_http_response(status, headers, body)
                self.fail_connection()
                await self.wait_closed()
                return

            try:
                await self.ws_handler(self, path)
            except Exception:
                logger.error("Error in connection handler", exc_info=True)
                if not self.closed:
                    self.fail_connection(1011)
                raise

            try:
                await self.close()
            except ConnectionError:
                logger.debug("Connection error in closing handshake", exc_info=True)
                raise
            except Exception:
                logger.warning("Error in closing handshake", exc_info=True)
                raise

        except Exception:
            # Last-ditch attempt to avoid leaking connections on errors.
            try:
                self.writer.close()
            except Exception:  # pragma: no cover
                pass

        finally:
            # Unregister the connection with the server when the handler task
            # terminates. Registration is tied to the lifecycle of the handler
            # task because the server waits for tasks attached to registered
            # connections before terminating.
            self.ws_server.unregister(self)