Search in sources :

Example 1 with RedirectException

use of org.xnio.http.RedirectException in project wildfly-core by wildfly.

the class ReloadHandler method ensureServerRebootComplete.

private void ensureServerRebootComplete(CommandContext ctx, ModelControllerClient client) throws CommandLineException {
    final long start = System.currentTimeMillis();
    final long timeoutMillis = ctx.getConfig().getConnectionTimeout() + 1000L;
    final ModelNode getStateOp = new ModelNode();
    if (ctx.isDomainMode()) {
        final ParsedCommandLine args = ctx.getParsedCommandLine();
        final String hostName = host.getValue(args);
        getStateOp.get(Util.ADDRESS).add(Util.HOST, hostName);
    }
    getStateOp.get(ClientConstants.OP).set(ClientConstants.READ_ATTRIBUTE_OPERATION);
    // this is left for compatibility with older hosts, it could use runtime-configuration-state on newer hosts.
    if (ctx.isDomainMode()) {
        getStateOp.get(ClientConstants.NAME).set("host-state");
    } else {
        getStateOp.get(ClientConstants.NAME).set("server-state");
    }
    while (true) {
        String serverState = null;
        try {
            final ModelNode response = client.execute(getStateOp);
            if (Util.isSuccess(response)) {
                serverState = response.get(ClientConstants.RESULT).asString();
                if ("running".equals(serverState) || "restart-required".equals(serverState)) {
                    // we're reloaded and the server is started
                    break;
                }
            }
        } catch (IOException e) {
            // A Redirect Exception? Need to connect again the Client
            // if that is an http to https redirect only.
            Throwable ex = e;
            while (ex != null) {
                if (ex instanceof RedirectException) {
                    // Attempt to reconnect the context
                    if (Util.reconnectContext((RedirectException) ex, ctx)) {
                        return;
                    }
                } else if (ex instanceof SaslException) {
                    // invalid (eg: change of security-realm or SASL reconfiguration).
                    try {
                        ctx.connectController();
                        return;
                    } catch (CommandLineException clex) {
                    // Not reconnected.
                    }
                }
                ex = ex.getCause();
            }
        // ignore and try again
        } catch (IllegalStateException ex) {
        // ignore and try again
        // IllegalStateException is because the embedded server ModelControllerClient will
        // throw that when the server-state / host-state is "stopping"
        }
        if (System.currentTimeMillis() - start > timeoutMillis) {
            if (!"starting".equals(serverState)) {
                ctx.disconnectController();
                throw new CommandLineException("Failed to establish connection in " + (System.currentTimeMillis() - start) + "ms");
            }
        // else we don't wait any longer for start to finish
        }
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            ctx.disconnectController();
            throw new CommandLineException("Interrupted while pausing before reconnecting.", e);
        }
    }
}
Also used : ParsedCommandLine(org.jboss.as.cli.operation.ParsedCommandLine) IOException(java.io.IOException) ModelNode(org.jboss.dmr.ModelNode) SaslException(javax.security.sasl.SaslException) CommandLineException(org.jboss.as.cli.CommandLineException) RedirectException(org.xnio.http.RedirectException)

Example 2 with RedirectException

use of org.xnio.http.RedirectException in project wildfly-core by wildfly.

the class CLIModelControllerClient method ensureConnected.

@Override
public void ensureConnected(long timeoutMillis) throws CommandLineException, IOException {
    boolean doTry = true;
    final long start = System.currentTimeMillis();
    IOException ioe = null;
    boolean timeoutOccured = false;
    while (doTry) {
        try {
            // Can't be called locked, could create dead lock if close occured.
            getOrCreateChannel().getConnection();
            doTry = false;
        } catch (IOException e) {
            ioe = e;
            synchronized (lock) {
                if (strategy != null) {
                    StreamUtils.safeClose(strategy);
                    strategy = null;
                }
                lock.notifyAll();
            }
        }
        if (ioe != null) {
            if (ioe.getCause() != null && ioe.getCause() instanceof SaslException) {
                throw new CommandLineException("Failed to establish connection", ioe);
            }
            if (System.currentTimeMillis() - start > timeoutMillis) {
                if (timeoutOccured) {
                    throw new CommandLineException("Failed to establish connection in " + (System.currentTimeMillis() - start) + "ms", ioe);
                } else {
                    timeoutOccured = true;
                }
            }
            // Only propagate RedirectException at the end of timeout.
            if (timeoutOccured) {
                Throwable ex = ioe;
                while (ex != null) {
                    if (ex instanceof RedirectException) {
                        // only http to https redirect.
                        try {
                            if (Util.isHttpsRedirect((RedirectException) ex, channelConfig.getUri().getScheme())) {
                                throw (RedirectException) ex;
                            }
                        } catch (URISyntaxException uriex) {
                        // XXX OK, would fail later.
                        }
                    }
                    ex = ex.getCause();
                }
            }
            ioe = null;
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new CommandLineException("Interrupted while pausing before reconnecting.", e);
            }
        }
    }
}
Also used : IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) SaslException(javax.security.sasl.SaslException) CommandLineException(org.jboss.as.cli.CommandLineException) RedirectException(org.xnio.http.RedirectException)

Example 3 with RedirectException

use of org.xnio.http.RedirectException in project OpenUnison by TremoloSecurity.

the class ConnectionBuilder method connectImpl.

private IoFuture<WebSocketChannel> connectImpl(final URI uri, final FutureResult<WebSocketChannel> ioFuture, final int redirectCount) {
    WebSocketLogger.REQUEST_LOGGER.debugf("Opening websocket connection to %s", uri);
    final String scheme = uri.getScheme().equals("wss") ? "https" : "http";
    final URI newUri;
    try {
        newUri = new URI(scheme, uri.getUserInfo(), uri.getHost(), uri.getPort() == -1 ? (uri.getScheme().equals("wss") ? 443 : 80) : uri.getPort(), uri.getPath().isEmpty() ? "/" : uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    final WebSocketClientHandshake handshake = WebSocketClientHandshake.create(version, newUri, clientNegotiation, clientExtensions);
    final Map<String, String> originalHeaders = handshake.createHeaders();
    originalHeaders.put(Headers.HOST_STRING, uri.getHost() + ":" + newUri.getPort());
    final Map<String, List<String>> headers = new HashMap<>();
    for (Map.Entry<String, String> entry : originalHeaders.entrySet()) {
        List<String> list = new ArrayList<>();
        list.add(entry.getValue());
        headers.put(entry.getKey(), list);
    }
    headers.putAll(this.additionalHeaders);
    if (clientNegotiation != null) {
        clientNegotiation.beforeRequest(headers);
    }
    InetSocketAddress toBind = bindAddress;
    String sysBind = System.getProperty(WebSocketClient.BIND_PROPERTY);
    if (toBind == null && sysBind != null) {
        toBind = new InetSocketAddress(sysBind, 0);
    }
    if (proxyUri != null) {
        UndertowClient.getInstance().connect(new ClientCallback<ClientConnection>() {

            @Override
            public void completed(final ClientConnection connection) {
                int port = uri.getPort() > 0 ? uri.getPort() : uri.getScheme().equals("https") || uri.getScheme().equals("wss") ? 443 : 80;
                ClientRequest cr = new ClientRequest().setMethod(Methods.CONNECT).setPath(uri.getHost() + ":" + port).setProtocol(Protocols.HTTP_1_1);
                cr.getRequestHeaders().put(Headers.HOST, proxyUri.getHost() + ":" + (proxyUri.getPort() > 0 ? proxyUri.getPort() : 80));
                connection.sendRequest(cr, new ClientCallback<ClientExchange>() {

                    @Override
                    public void completed(ClientExchange result) {
                        result.setResponseListener(new ClientCallback<ClientExchange>() {

                            @Override
                            public void completed(ClientExchange response) {
                                try {
                                    if (response.getResponse().getResponseCode() == 200) {
                                        try {
                                            StreamConnection targetConnection = connection.performUpgrade();
                                            WebSocketLogger.REQUEST_LOGGER.debugf("Established websocket connection to %s", uri);
                                            if (uri.getScheme().equals("wss") || uri.getScheme().equals("https")) {
                                                handleConnectionWithExistingConnection(((UndertowXnioSsl) ssl).wrapExistingConnection(targetConnection, optionMap));
                                            } else {
                                                handleConnectionWithExistingConnection(targetConnection);
                                            }
                                        } catch (IOException e) {
                                            ioFuture.setException(e);
                                        } catch (Exception e) {
                                            ioFuture.setException(new IOException(e));
                                        }
                                    } else {
                                        ioFuture.setException(UndertowMessages.MESSAGES.proxyConnectionFailed(response.getResponse().getResponseCode()));
                                    }
                                } catch (Exception e) {
                                    ioFuture.setException(new IOException(e));
                                }
                            }

                            private void handleConnectionWithExistingConnection(StreamConnection targetConnection) {
                                final IoFuture<?> result;
                                result = HttpUpgrade.performUpgrade(targetConnection, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), handshake.handshakeChecker(newUri, headers));
                                result.addNotifier(new IoFuture.Notifier<Object, Object>() {

                                    @Override
                                    public void notify(IoFuture<?> res, Object attachment) {
                                        if (res.getStatus() == IoFuture.Status.FAILED) {
                                            ioFuture.setException(res.getException());
                                        }
                                    }
                                }, null);
                                ioFuture.addCancelHandler(new Cancellable() {

                                    @Override
                                    public Cancellable cancel() {
                                        result.cancel();
                                        return null;
                                    }
                                });
                            }

                            @Override
                            public void failed(IOException e) {
                                ioFuture.setException(e);
                            }
                        });
                    }

                    @Override
                    public void failed(IOException e) {
                        ioFuture.setException(e);
                    }
                });
            }

            @Override
            public void failed(IOException e) {
                ioFuture.setException(e);
            }
        }, bindAddress, proxyUri, worker, proxySsl, bufferPool, optionMap);
    } else {
        final IoFuture<?> result;
        if (ssl != null) {
            result = HttpUpgrade.performUpgrade(worker, ssl, toBind, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), null, optionMap, handshake.handshakeChecker(newUri, headers));
        } else {
            result = HttpUpgrade.performUpgrade(worker, toBind, newUri, headers, new WebsocketConnectionListener(optionMap, handshake, newUri, ioFuture), null, optionMap, handshake.handshakeChecker(newUri, headers));
        }
        result.addNotifier(new IoFuture.Notifier<Object, Object>() {

            @Override
            public void notify(IoFuture<?> res, Object attachment) {
                if (res.getStatus() == IoFuture.Status.FAILED) {
                    IOException exception = res.getException();
                    if (exception instanceof RedirectException) {
                        if (redirectCount == MAX_REDIRECTS) {
                            ioFuture.setException(UndertowMessages.MESSAGES.tooManyRedirects(exception));
                        } else {
                            String path = ((RedirectException) exception).getLocation();
                            try {
                                connectImpl(new URI(path), ioFuture, redirectCount + 1);
                            } catch (URISyntaxException e) {
                                ioFuture.setException(new IOException(e));
                            }
                        }
                    } else {
                        ioFuture.setException(exception);
                    }
                }
            }
        }, null);
        ioFuture.addCancelHandler(new Cancellable() {

            @Override
            public Cancellable cancel() {
                result.cancel();
                return null;
            }
        });
    }
    return ioFuture.getIoFuture();
}
Also used : ClientExchange(io.undertow.client.ClientExchange) ClientCallback(io.undertow.client.ClientCallback) HashMap(java.util.HashMap) InetSocketAddress(java.net.InetSocketAddress) Cancellable(org.xnio.Cancellable) ArrayList(java.util.ArrayList) IoFuture(org.xnio.IoFuture) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) ArrayList(java.util.ArrayList) List(java.util.List) ClientConnection(io.undertow.client.ClientConnection) ClientRequest(io.undertow.client.ClientRequest) WebSocketClientHandshake(io.undertow.websockets.client.WebSocketClientHandshake) IOException(java.io.IOException) StreamConnection(org.xnio.StreamConnection) RedirectException(org.xnio.http.RedirectException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) UndertowXnioSsl(io.undertow.protocols.ssl.UndertowXnioSsl) HashMap(java.util.HashMap) OptionMap(org.xnio.OptionMap) Map(java.util.Map) RedirectException(org.xnio.http.RedirectException)

Example 4 with RedirectException

use of org.xnio.http.RedirectException in project wildfly-core by wildfly.

the class ShutdownHandler method doHandle.

/* (non-Javadoc)
     * @see org.jboss.as.cli.handlers.CommandHandlerWithHelp#doHandle(org.jboss.as.cli.CommandContext)
     */
@Override
protected void doHandle(CommandContext ctx) throws CommandLineException {
    final ModelControllerClient client = ctx.getModelControllerClient();
    if (client == null) {
        throw new CommandLineException("Connection is not available.");
    }
    if (embeddedServerRef != null && embeddedServerRef.get() != null) {
        embeddedServerRef.get().stop();
        return;
    }
    if (!(client instanceof AwaiterModelControllerClient)) {
        throw new CommandLineException("Unsupported ModelControllerClient implementation " + client.getClass().getName());
    }
    final AwaiterModelControllerClient cliClient = (AwaiterModelControllerClient) client;
    final ModelNode op = this.buildRequestWithoutHeaders(ctx);
    boolean disconnect = true;
    final String restartValue = restart.getValue(ctx.getParsedCommandLine());
    if (Util.TRUE.equals(restartValue) || ctx.isDomainMode() && !isLocalHost(ctx.getModelControllerClient(), host.getValue(ctx.getParsedCommandLine()))) {
        disconnect = false;
    }
    try {
        final ModelNode response = cliClient.execute(op, true);
        if (!Util.isSuccess(response)) {
            throw new CommandLineException(Util.getFailureDescription(response));
        }
    } catch (IOException e) {
        // if it's not connected, it's assumed the connection has already been shutdown
        if (cliClient.isConnected()) {
            StreamUtils.safeClose(client);
            throw new CommandLineException("Failed to execute :shutdown", e);
        }
    }
    if (disconnect) {
        ctx.disconnectController();
    } else {
        // waiting half a sec on my machine works perfectly
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new CommandLineException("Interrupted while pausing before reconnecting.", e);
        }
        try {
            cliClient.ensureConnected(ctx.getConfig().getConnectionTimeout() + 1000L);
        } catch (CommandLineException e) {
            ctx.disconnectController();
            throw e;
        } catch (IOException ex) {
            if (ex instanceof RedirectException) {
                if (!Util.reconnectContext((RedirectException) ex, ctx)) {
                    throw new CommandLineException("Can't reconnect context.", ex);
                }
            } else {
                throw new CommandLineException(ex);
            }
        }
    }
}
Also used : AwaiterModelControllerClient(org.jboss.as.cli.AwaiterModelControllerClient) ModelControllerClient(org.jboss.as.controller.client.ModelControllerClient) IOException(java.io.IOException) AwaiterModelControllerClient(org.jboss.as.cli.AwaiterModelControllerClient) ModelNode(org.jboss.dmr.ModelNode) CommandLineException(org.jboss.as.cli.CommandLineException) RedirectException(org.xnio.http.RedirectException)

Example 5 with RedirectException

use of org.xnio.http.RedirectException in project wildfly-core by wildfly.

the class CommandContextImpl method tryConnection.

/**
 * Used to make a call to the server to verify that it is possible to connect.
 */
private void tryConnection(final ModelControllerClient client, ControllerAddress address) throws CommandLineException, RedirectException {
    try {
        DefaultOperationRequestBuilder builder = new DefaultOperationRequestBuilder();
        builder.setOperationName(Util.READ_ATTRIBUTE);
        builder.addProperty(Util.NAME, Util.NAME);
        final long start = System.currentTimeMillis();
        final long timeoutMillis = config.getConnectionTimeout() + 1000L;
        boolean tryConnection = true;
        while (tryConnection) {
            final ModelNode response = client.execute(builder.buildRequest());
            if (!Util.isSuccess(response)) {
                // here we check whether the error is related to the access control permissions
                // WFLYCTL0332: Permission denied
                // WFLYCTL0313: Unauthorized to execute operation
                final String failure = Util.getFailureDescription(response);
                if (failure.contains("WFLYCTL0332")) {
                    StreamUtils.safeClose(client);
                    throw new CommandLineException("Connection refused based on the insufficient user permissions." + " Please, make sure the security-realm attribute is specified for the relevant management interface" + " (standalone.xml/host.xml) and review the access-control configuration (standalone.xml/domain.xml).");
                } else if (failure.contains("WFLYCTL0379")) {
                    // system boot is in process
                    if (System.currentTimeMillis() - start > timeoutMillis) {
                        throw new CommandLineException("Timeout waiting for the system to boot.");
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        disconnectController();
                        throw new CommandLineException("Interrupted while pausing before trying connection.", e);
                    }
                } else {
                    // Otherwise, on one hand, we don't actually care what the response is,
                    // we just want to be sure the ModelControllerClient does not throw an Exception.
                    // On the other hand, reading name attribute is a very basic one which should always work
                    printLine("Warning! The connection check resulted in failure: " + Util.getFailureDescription(response));
                    tryConnection = false;
                }
            } else {
                tryConnection = false;
            }
        }
    } catch (Exception e) {
        try {
            Throwable current = e;
            while (current != null) {
                if (current instanceof SaslException) {
                    throw new CommandLineException("Unable to authenticate against controller at " + address.getHost() + ":" + address.getPort(), current);
                }
                if (current instanceof SSLException) {
                    throw new CommandLineException("Unable to negotiate SSL connection with controller at " + address.getHost() + ":" + address.getPort());
                }
                if (current instanceof RedirectException) {
                    throw (RedirectException) current;
                }
                if (current instanceof CommandLineException) {
                    throw (CommandLineException) current;
                }
                current = current.getCause();
            }
            // We don't know what happened, most likely a timeout.
            throw new CommandLineException("The controller is not available at " + address.getHost() + ":" + address.getPort(), e);
        } finally {
            StreamUtils.safeClose(client);
        }
    }
}
Also used : DefaultOperationRequestBuilder(org.jboss.as.cli.operation.impl.DefaultOperationRequestBuilder) ModelNode(org.jboss.dmr.ModelNode) SaslException(javax.security.sasl.SaslException) SSLException(javax.net.ssl.SSLException) CommandLineException(org.jboss.as.cli.CommandLineException) SaslException(javax.security.sasl.SaslException) GeneralSecurityException(java.security.GeneralSecurityException) CommandFormatException(org.jboss.as.cli.CommandFormatException) AccessDeniedException(java.nio.file.AccessDeniedException) IOException(java.io.IOException) CommandLineException(org.jboss.as.cli.CommandLineException) ExecutionException(java.util.concurrent.ExecutionException) URISyntaxException(java.net.URISyntaxException) CommandLineParserException(org.aesh.command.parser.CommandLineParserException) UnsupportedCallbackException(javax.security.auth.callback.UnsupportedCallbackException) SSLException(javax.net.ssl.SSLException) Assert.checkNotNullParamWithNullPointerException(org.wildfly.common.Assert.checkNotNullParamWithNullPointerException) TimeoutException(java.util.concurrent.TimeoutException) OperationFormatException(org.jboss.as.cli.operation.OperationFormatException) RedirectException(org.xnio.http.RedirectException) CliInitializationException(org.jboss.as.cli.CliInitializationException) CommandNotFoundException(org.aesh.command.CommandNotFoundException) OptionValidatorException(org.aesh.command.validator.OptionValidatorException) CertificateException(java.security.cert.CertificateException) RedirectException(org.xnio.http.RedirectException)

Aggregations

IOException (java.io.IOException)6 RedirectException (org.xnio.http.RedirectException)6 CommandLineException (org.jboss.as.cli.CommandLineException)5 URISyntaxException (java.net.URISyntaxException)4 SaslException (javax.security.sasl.SaslException)3 ModelNode (org.jboss.dmr.ModelNode)3 URI (java.net.URI)2 ModelControllerClient (org.jboss.as.controller.client.ModelControllerClient)2 ClientCallback (io.undertow.client.ClientCallback)1 ClientConnection (io.undertow.client.ClientConnection)1 ClientExchange (io.undertow.client.ClientExchange)1 ClientRequest (io.undertow.client.ClientRequest)1 UndertowXnioSsl (io.undertow.protocols.ssl.UndertowXnioSsl)1 WebSocketClientHandshake (io.undertow.websockets.client.WebSocketClientHandshake)1 InetSocketAddress (java.net.InetSocketAddress)1 AccessDeniedException (java.nio.file.AccessDeniedException)1 GeneralSecurityException (java.security.GeneralSecurityException)1 CertificateException (java.security.cert.CertificateException)1 ArrayList (java.util.ArrayList)1 Date (java.util.Date)1