Search in sources :

Example 26 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class WebSocketProvider method start.

@Override
public void start() {
    _idleTimeoutChecker.start();
    _server = new Server(new QBBTrackingThreadPool());
    final ServerConnector connector;
    HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory();
    httpConnectionFactory.getHttpConfiguration().setSendServerVersion(false);
    httpConnectionFactory.getHttpConfiguration().setSendXPoweredBy(false);
    if (_transport == Transport.WS) {
        connector = new ServerConnector(_server, httpConnectionFactory);
    } else if (_transport == Transport.WSS) {
        SslContextFactory sslContextFactory = new SslContextFactory() {

            @Override
            public void customize(final SSLEngine sslEngine) {
                super.customize(sslEngine);
                SSLUtil.updateEnabledCipherSuites(sslEngine, _port.getTlsCipherSuiteWhiteList(), _port.getTlsCipherSuiteBlackList());
                SSLUtil.updateEnabledTlsProtocols(sslEngine, _port.getTlsProtocolWhiteList(), _port.getTlsProtocolBlackList());
                if (_port.getTlsCipherSuiteWhiteList() != null && !_port.getTlsCipherSuiteWhiteList().isEmpty()) {
                    SSLParameters sslParameters = sslEngine.getSSLParameters();
                    sslParameters.setUseCipherSuitesOrder(true);
                    sslEngine.setSSLParameters(sslParameters);
                }
            }
        };
        sslContextFactory.setSslContext(_sslContext);
        sslContextFactory.setNeedClientAuth(_port.getNeedClientAuth());
        sslContextFactory.setWantClientAuth(_port.getWantClientAuth());
        connector = new ServerConnector(_server, sslContextFactory, httpConnectionFactory);
        connector.addBean(new SslHandshakeListener() {

            @Override
            public void handshakeFailed(final Event event, final Throwable failure) {
                SSLEngine sslEngine = event.getSSLEngine();
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.info("TLS handshake failed: host='{}', port={}", sslEngine.getPeerHost(), sslEngine.getPeerPort(), failure);
                } else {
                    LOGGER.info("TLS handshake failed: host='{}', port={}: {}", sslEngine.getPeerHost(), sslEngine.getPeerPort(), String.valueOf(failure));
                }
            }
        });
    } else {
        throw new IllegalArgumentException("Unexpected transport on port " + _port.getName() + ":" + _transport);
    }
    String bindingAddress = _port.getBindingAddress();
    if (bindingAddress != null && !bindingAddress.trim().equals("") && !bindingAddress.trim().equals("*")) {
        connector.setHost(bindingAddress.trim());
    }
    connector.setPort(_port.getPort());
    _server.addConnector(connector);
    WebSocketHandler wshandler = new WebSocketHandler() {

        @Override
        public void configure(final WebSocketServletFactory factory) {
            factory.setCreator((req, resp) -> {
                resp.setAcceptedSubProtocol(AMQP_WEBSOCKET_SUBPROTOCOL);
                return new AmqpWebSocket();
            });
        }

        @Override
        public void configurePolicy(final WebSocketPolicy policy) {
            super.configurePolicy(policy);
            // See https://github.com/eclipse/jetty.project/issues/488
            try {
                Field maxBinaryMessageSize = policy.getClass().getDeclaredField("maxBinaryMessageSize");
                maxBinaryMessageSize.setAccessible(true);
                maxBinaryMessageSize.set(policy, 0);
            } catch (IllegalAccessException | NoSuchFieldException e) {
                LOGGER.warn("Could not override maxBinaryMessageSize", e);
            }
        }
    };
    _server.setHandler(wshandler);
    wshandler.setHandler(new AbstractHandler() {

        @Override
        public void handle(final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {
            if (response.isCommitted() || baseRequest.isHandled()) {
                return;
            }
            baseRequest.setHandled(true);
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        }
    });
    try {
        _server.start();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new ServerScopedRuntimeException(e);
    }
}
Also used : WebSocketServletFactory(org.eclipse.jetty.websocket.servlet.WebSocketServletFactory) Server(org.eclipse.jetty.server.Server) SslHandshakeListener(org.eclipse.jetty.io.ssl.SslHandshakeListener) SSLEngine(javax.net.ssl.SSLEngine) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) Field(java.lang.reflect.Field) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) SSLParameters(javax.net.ssl.SSLParameters) WebSocketPolicy(org.eclipse.jetty.websocket.api.WebSocketPolicy) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletUpgradeRequest(org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) IOException(java.io.IOException) WebSocketHandler(org.eclipse.jetty.websocket.server.WebSocketHandler)

Example 27 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class AbstractQueue method addConsumerInternal.

private <T extends ConsumerTarget<T>> QueueConsumerImpl<T> addConsumerInternal(final T target, FilterManager filters, final Class<? extends ServerMessage> messageClass, final String consumerName, EnumSet<ConsumerOption> optionSet, final Integer priority) throws ExistingExclusiveConsumer, ConsumerAccessRefused, ExistingConsumerPreventsExclusive, QueueDeleted {
    if (isDeleted()) {
        throw new QueueDeleted();
    }
    if (hasExclusiveConsumer()) {
        throw new ExistingExclusiveConsumer();
    }
    Object exclusiveOwner = _exclusiveOwner;
    final AMQPSession<?, T> session = target.getSession();
    switch(_exclusive) {
        case CONNECTION:
            if (exclusiveOwner == null) {
                exclusiveOwner = session.getAMQPConnection();
                addExclusivityConstraint(session.getAMQPConnection());
            } else {
                if (exclusiveOwner != session.getAMQPConnection()) {
                    throw new ConsumerAccessRefused();
                }
            }
            break;
        case SESSION:
            if (exclusiveOwner == null) {
                exclusiveOwner = session;
                addExclusivityConstraint(session);
            } else {
                if (exclusiveOwner != session) {
                    throw new ConsumerAccessRefused();
                }
            }
            break;
        case LINK:
            if (getConsumerCount() != 0) {
                throw new ConsumerAccessRefused();
            }
            break;
        case PRINCIPAL:
            Principal currentAuthorizedPrincipal = session.getAMQPConnection().getAuthorizedPrincipal();
            if (exclusiveOwner == null) {
                exclusiveOwner = currentAuthorizedPrincipal;
            } else {
                if (!Objects.equals(((Principal) exclusiveOwner).getName(), currentAuthorizedPrincipal.getName())) {
                    throw new ConsumerAccessRefused();
                }
            }
            break;
        case CONTAINER:
            if (exclusiveOwner == null) {
                exclusiveOwner = session.getAMQPConnection().getRemoteContainerName();
            } else {
                if (!exclusiveOwner.equals(session.getAMQPConnection().getRemoteContainerName())) {
                    throw new ConsumerAccessRefused();
                }
            }
            break;
        case SHARED_SUBSCRIPTION:
            break;
        case NONE:
            break;
        default:
            throw new ServerScopedRuntimeException("Unknown exclusivity policy " + _exclusive);
    }
    boolean exclusive = optionSet.contains(ConsumerOption.EXCLUSIVE);
    boolean isTransient = optionSet.contains(ConsumerOption.TRANSIENT);
    if (_noLocal && !optionSet.contains(ConsumerOption.NO_LOCAL)) {
        optionSet = EnumSet.copyOf(optionSet);
        optionSet.add(ConsumerOption.NO_LOCAL);
    }
    if (exclusive && getConsumerCount() != 0) {
        throw new ExistingConsumerPreventsExclusive();
    }
    if (!_defaultFiltersMap.isEmpty()) {
        if (filters == null) {
            filters = new FilterManager();
        }
        for (Map.Entry<String, Callable<MessageFilter>> filter : _defaultFiltersMap.entrySet()) {
            if (!filters.hasFilter(filter.getKey())) {
                MessageFilter f;
                try {
                    f = filter.getValue().call();
                } catch (Exception e) {
                    if (e instanceof RuntimeException) {
                        throw (RuntimeException) e;
                    } else {
                        // Should never happen
                        throw new ServerScopedRuntimeException(e);
                    }
                }
                filters.add(filter.getKey(), f);
            }
        }
    }
    if (_ensureNondestructiveConsumers) {
        optionSet = EnumSet.copyOf(optionSet);
        optionSet.removeAll(EnumSet.of(ConsumerOption.SEES_REQUEUES, ConsumerOption.ACQUIRES));
    }
    QueueConsumerImpl<T> consumer = new QueueConsumerImpl<>(this, target, consumerName, filters, messageClass, optionSet, priority);
    _exclusiveOwner = exclusiveOwner;
    if (exclusive && !isTransient) {
        _exclusiveSubscriber = consumer;
    }
    QueueContext queueContext;
    if (filters == null || !filters.startAtTail()) {
        queueContext = new QueueContext(getEntries().getHead());
    } else {
        queueContext = new QueueContext(getEntries().getTail());
    }
    consumer.setQueueContext(queueContext);
    _queueConsumerManager.addConsumer(consumer);
    if (consumer.isNotifyWorkDesired()) {
        _activeSubscriberCount.incrementAndGet();
    }
    childAdded(consumer);
    consumer.addChangeListener(_deletedChildListener);
    session.incConsumerCount();
    addChangeListener(new AbstractConfigurationChangeListener() {

        @Override
        public void childRemoved(final ConfiguredObject<?> object, final ConfiguredObject<?> child) {
            if (child.equals(consumer)) {
                session.decConsumerCount();
                removeChangeListener(this);
            }
        }
    });
    return consumer;
}
Also used : Callable(java.util.concurrent.Callable) SelectorParsingException(org.apache.qpid.server.filter.SelectorParsingException) MessageDestinationIsAlternateException(org.apache.qpid.server.virtualhost.MessageDestinationIsAlternateException) ParseException(org.apache.qpid.server.filter.selector.ParseException) VirtualHostUnavailableException(org.apache.qpid.server.virtualhost.VirtualHostUnavailableException) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) UnknownAlternateBindingException(org.apache.qpid.server.virtualhost.UnknownAlternateBindingException) MessageDeletedException(org.apache.qpid.server.message.MessageDeletedException) IOException(java.io.IOException) AccessControlException(java.security.AccessControlException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) FilterManager(org.apache.qpid.server.filter.FilterManager) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) MessageFilter(org.apache.qpid.server.filter.MessageFilter) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) GenericPrincipal(org.apache.qpid.server.model.preferences.GenericPrincipal) SessionPrincipal(org.apache.qpid.server.connection.SessionPrincipal) Principal(java.security.Principal) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal)

Example 28 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class FileKeyStoreImpl method validateKeyStoreAttributes.

private void validateKeyStoreAttributes(FileKeyStore<?> fileKeyStore) {
    java.security.KeyStore keyStore;
    try {
        URL url = getUrlFromString(fileKeyStore.getStoreUrl());
        String password = fileKeyStore.getPassword();
        String keyStoreType = fileKeyStore.getKeyStoreType();
        keyStore = SSLUtil.getInitializedKeyStore(url, password, keyStoreType);
    } catch (Exception e) {
        final String message;
        if (e instanceof IOException && e.getCause() != null && e.getCause() instanceof UnrecoverableKeyException) {
            message = "Check key store password. Cannot instantiate key store from '" + fileKeyStore.getStoreUrl() + "'.";
        } else {
            message = "Cannot instantiate key store from '" + fileKeyStore.getStoreUrl() + "'.";
        }
        throw new IllegalConfigurationException(message, e);
    }
    try {
        final String certAlias = fileKeyStore.getCertificateAlias();
        if (certAlias != null) {
            Certificate cert = keyStore.getCertificate(certAlias);
            if (cert == null) {
                throw new IllegalConfigurationException(String.format("Cannot find a certificate with alias '%s' in key store : %s", certAlias, fileKeyStore.getStoreUrl()));
            }
            if (keyStore.isCertificateEntry(certAlias)) {
                throw new IllegalConfigurationException(String.format("Alias '%s' in key store : %s does not identify a key.", certAlias, fileKeyStore.getStoreUrl()));
            }
        }
        if (!containsPrivateKey(keyStore)) {
            throw new IllegalConfigurationException("Keystore must contain at least one private key.");
        }
    } catch (KeyStoreException e) {
        // key store should be initialized above
        throw new ServerScopedRuntimeException("Key store has not been initialized", e);
    }
    try {
        KeyManagerFactory.getInstance(fileKeyStore.getKeyManagerFactoryAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalConfigurationException("Unknown keyManagerFactoryAlgorithm: " + fileKeyStore.getKeyManagerFactoryAlgorithm());
    }
    if (!fileKeyStore.isDurable()) {
        throw new IllegalArgumentException(getClass().getSimpleName() + " must be durable");
    }
    checkCertificateExpiry();
}
Also used : IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) IOException(java.io.IOException) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) URL(java.net.URL) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) Certificate(java.security.cert.Certificate)

Example 29 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class MD5AuthenticationProvider method createStoredPassword.

@Override
protected String createStoredPassword(final String password) {
    byte[] data = password.getBytes(StandardCharsets.UTF_8);
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new ServerScopedRuntimeException("MD5 not supported although Java compliance requires it");
    }
    md.update(data);
    return DatatypeConverter.printBase64Binary(md.digest());
}
Also used : NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MessageDigest(java.security.MessageDigest) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException)

Example 30 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class AbstractConsumerTarget method sendNextMessage.

@Override
public boolean sendNextMessage() {
    MessageContainer messageContainer = null;
    MessageInstanceConsumer consumer = null;
    boolean iteratedCompleteList = false;
    while (messageContainer == null) {
        if (_pullIterator == null || !_pullIterator.hasNext()) {
            if (iteratedCompleteList) {
                break;
            }
            iteratedCompleteList = true;
            _pullIterator = getConsumers().iterator();
        }
        if (_pullIterator.hasNext()) {
            consumer = _pullIterator.next();
            messageContainer = consumer.pullMessage();
        }
    }
    if (messageContainer != null) {
        MessageInstance entry = messageContainer.getMessageInstance();
        try {
            send(consumer, entry, false);
        } catch (MessageConversionException mce) {
            restoreCredit(entry.getMessage());
            final TransactionLogResource owningResource = entry.getOwningResource();
            if (owningResource instanceof MessageSource) {
                final MessageSource.MessageConversionExceptionHandlingPolicy handlingPolicy = ((MessageSource) owningResource).getMessageConversionExceptionHandlingPolicy();
                switch(handlingPolicy) {
                    case CLOSE:
                        entry.release(consumer);
                        throw new ConnectionScopedRuntimeException(String.format("Unable to convert message %s for this consumer", entry.getMessage()), mce);
                    case ROUTE_TO_ALTERNATE:
                        if (consumer.acquires()) {
                            int enqueues = entry.routeToAlternate(null, null);
                            if (enqueues == 0) {
                                LOGGER.info("Failed to convert message {} for this consumer because '{}'." + "  Message discarded.", entry.getMessage(), mce.getMessage());
                            } else {
                                LOGGER.info("Failed to convert message {} for this consumer because '{}'." + "  Message routed to alternate.", entry.getMessage(), mce.getMessage());
                            }
                        } else {
                            LOGGER.info("Failed to convert message {} for this browser because '{}'." + "  Message skipped.", entry.getMessage(), mce.getMessage());
                        }
                        break;
                    case REJECT:
                        entry.reject(consumer);
                        entry.release(consumer);
                        LOGGER.info("Failed to convert message {} for this consumer because '{}'." + "  Message skipped.", entry.getMessage(), mce.getMessage());
                        break;
                    default:
                        throw new ServerScopedRuntimeException("Unrecognised policy " + handlingPolicy);
                }
            } else {
                throw new ConnectionScopedRuntimeException(String.format("Unable to convert message %s for this consumer", entry.getMessage()), mce);
            }
        } finally {
            if (messageContainer.getMessageReference() != null) {
                messageContainer.getMessageReference().release();
            }
        }
        return true;
    } else {
        return false;
    }
}
Also used : MessageInstance(org.apache.qpid.server.message.MessageInstance) MessageConversionException(org.apache.qpid.server.protocol.converter.MessageConversionException) MessageContainer(org.apache.qpid.server.message.MessageContainer) ConnectionScopedRuntimeException(org.apache.qpid.server.util.ConnectionScopedRuntimeException) MessageInstanceConsumer(org.apache.qpid.server.message.MessageInstanceConsumer) MessageSource(org.apache.qpid.server.message.MessageSource) TransactionLogResource(org.apache.qpid.server.store.TransactionLogResource) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException)

Aggregations

ServerScopedRuntimeException (org.apache.qpid.server.util.ServerScopedRuntimeException)45 IOException (java.io.IOException)17 GeneralSecurityException (java.security.GeneralSecurityException)10 Map (java.util.Map)10 ConnectionScopedRuntimeException (org.apache.qpid.server.util.ConnectionScopedRuntimeException)10 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)9 URL (java.net.URL)9 InputStream (java.io.InputStream)8 HttpURLConnection (java.net.HttpURLConnection)8 ConnectionBuilder (org.apache.qpid.server.util.ConnectionBuilder)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 IllegalConfigurationException (org.apache.qpid.server.configuration.IllegalConfigurationException)6 TrustStore (org.apache.qpid.server.model.TrustStore)6 UsernamePrincipal (org.apache.qpid.server.security.auth.UsernamePrincipal)6 IdentityResolverException (org.apache.qpid.server.security.auth.manager.oauth2.IdentityResolverException)6 Field (java.lang.reflect.Field)5 Method (java.lang.reflect.Method)4 ArrayList (java.util.ArrayList)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3