Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AbstractHandlerDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AbstractHandlerDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AbstractHandlerDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,104 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+import io.undertow.server.HttpHandler;
+import org.jboss.as.controller.AbstractAddStepHandler;
+import org.jboss.as.controller.AbstractRemoveStepHandler;
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.as.controller.PathElement;
+import org.jboss.as.controller.PersistentResourceDefinition;
+import org.jboss.as.controller.access.constraint.SensitivityClassification;
+import org.jboss.as.controller.access.management.AccessConstraintDefinition;
+import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
+import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+import org.jboss.as.controller.registry.OperationEntry;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+public abstract class AbstractHandlerDefinition extends PersistentResourceDefinition implements Handler {
+
+ private static final List CONSTRAINTS = new SensitiveTargetAccessConstraintDefinition(
+ new SensitivityClassification(UndertowExtension.SUBSYSTEM_NAME, "undertow-filter", false, false, false)
+ ).wrapAsList();
+
+ protected AbstractHandlerDefinition(final String name, AbstractAddStepHandler addHandler, AbstractRemoveStepHandler removeHandler) {
+ this(name, Constants.HANDLER, addHandler, removeHandler);
+ }
+
+ protected AbstractHandlerDefinition(final String name) {
+ this(name, Constants.HANDLER);
+ }
+
+ protected AbstractHandlerDefinition(final String name, String prefix, AbstractAddStepHandler addHandler, AbstractRemoveStepHandler removeHandler) {
+ super(PathElement.pathElement(name), UndertowExtension.getResolver(prefix, name), addHandler, removeHandler);
+ }
+
+ protected AbstractHandlerDefinition(final String name, String prefix) {
+ super(PathElement.pathElement(name), UndertowExtension.getResolver(prefix, name));
+ }
+
+ protected AbstractHandlerDefinition(final Parameters parameters) {
+ super(parameters);
+ }
+
+ @Override
+ public void registerOperations(ManagementResourceRegistration resourceRegistration) {
+ super.registerOperations(resourceRegistration);
+ if (resourceRegistration.getOperationEntry(PathAddress.EMPTY_ADDRESS, ModelDescriptionConstants.ADD) == null) {
+ registerAddOperation(resourceRegistration, new AbstractAddStepHandler(getAttributes()), OperationEntry.Flag.RESTART_RESOURCE_SERVICES);
+ }
+ if (resourceRegistration.getOperationEntry(PathAddress.EMPTY_ADDRESS, ModelDescriptionConstants.REMOVE) == null) {
+ registerRemoveOperation(resourceRegistration, new DefaultHandlerRemove(), OperationEntry.Flag.RESTART_RESOURCE_SERVICES);
+ }
+ }
+
+ @Override
+ public Class extends HttpHandler> getHandlerClass() {
+ return null;
+ }
+
+ @Override
+ public List getAccessConstraints() {
+ return CONSTRAINTS;
+ }
+
+ @Override
+ public Collection getAttributes() {
+ return Collections.emptyList();
+ }
+
+ protected static class DefaultHandlerRemove extends AbstractRemoveStepHandler {
+ private DefaultHandlerRemove() {
+
+ }
+ }
+
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AbstractPersistentSessionManager.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AbstractPersistentSessionManager.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AbstractPersistentSessionManager.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,182 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.wildfly.extension.undertow;
+
+import io.undertow.servlet.UndertowServletLogger;
+import io.undertow.servlet.api.SessionPersistenceManager;
+import org.jboss.marshalling.ByteBufferInput;
+import org.jboss.marshalling.Marshaller;
+import org.jboss.marshalling.MarshallerFactory;
+import org.jboss.marshalling.MarshallingConfiguration;
+import org.jboss.marshalling.ModularClassResolver;
+import org.jboss.marshalling.OutputStreamByteOutput;
+import org.jboss.marshalling.Unmarshaller;
+import org.jboss.marshalling.river.RiverMarshallerFactory;
+import org.jboss.modules.ModuleLoader;
+import org.jboss.msc.service.Service;
+import org.jboss.msc.service.ServiceName;
+import org.jboss.msc.service.StartContext;
+import org.jboss.msc.service.StartException;
+import org.jboss.msc.service.StopContext;
+import org.jboss.msc.value.InjectedValue;
+import org.wildfly.extension.undertow.logging.UndertowLogger;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Persistent session manager
+ *
+ * @author Stuart Douglas
+ */
+public abstract class AbstractPersistentSessionManager implements SessionPersistenceManager, Service {
+
+ public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("undertow", "persistent-session-manager");
+
+ private MarshallerFactory factory;
+ private MarshallingConfiguration configuration;
+
+ private final InjectedValue moduleLoaderInjectedValue = new InjectedValue<>();
+
+ @Override
+ public void persistSessions(String deploymentName, Map sessionData) {
+ try {
+ final Marshaller marshaller = createMarshaller();
+ try {
+ final Map serializedData = new HashMap();
+ for (Map.Entry sessionEntry : sessionData.entrySet()) {
+ Map data = new HashMap();
+ for (Map.Entry sessionAttribute : sessionEntry.getValue().getSessionData().entrySet()) {
+ try {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream();
+ marshaller.start(new OutputStreamByteOutput(out));
+ marshaller.writeObject(sessionAttribute.getValue());
+ marshaller.finish();
+ data.put(sessionAttribute.getKey(), out.toByteArray());
+ } catch (Exception e) {
+ UndertowLogger.ROOT_LOGGER.failedToPersistSessionAttribute(sessionAttribute.getKey(), sessionAttribute.getValue(), sessionEntry.getKey(), e);
+ }
+ }
+ serializedData.put(sessionEntry.getKey(), new SessionEntry(sessionEntry.getValue().getExpiration(), data));
+ }
+ persistSerializedSessions(deploymentName, serializedData);
+ } finally {
+ marshaller.close();
+ }
+ } catch (Exception e) {
+ UndertowServletLogger.ROOT_LOGGER.failedToPersistSessions(e);
+ }
+
+ }
+
+ protected abstract void persistSerializedSessions(String deploymentName, Map serializedData) throws IOException;
+
+ protected abstract Map loadSerializedSessions(final String deploymentName) throws IOException;
+
+ @Override
+ public Map loadSessionAttributes(String deploymentName, final ClassLoader classLoader) {
+ try {
+ Unmarshaller unmarshaller = createUnmarshaller();
+ try {
+ long time = System.currentTimeMillis();
+ Map data = loadSerializedSessions(deploymentName);
+ if (data != null) {
+ Map ret = new HashMap();
+ for (Map.Entry sessionEntry : data.entrySet()) {
+ if (sessionEntry.getValue().expiry.getTime() > time) {
+ Map session = new HashMap();
+ for (Map.Entry sessionAttribute : sessionEntry.getValue().data.entrySet()) {
+ unmarshaller.start(new ByteBufferInput(ByteBuffer.wrap(sessionAttribute.getValue())));
+ session.put(sessionAttribute.getKey(), unmarshaller.readObject());
+ unmarshaller.finish();
+ }
+ ret.put(sessionEntry.getKey(), new PersistentSession(sessionEntry.getValue().expiry, session));
+ }
+ }
+ return ret;
+ }
+ } finally {
+ unmarshaller.close();
+ }
+ } catch (Exception e) {
+ UndertowServletLogger.ROOT_LOGGER.failedtoLoadPersistentSessions(e);
+ }
+ return null;
+ }
+
+ protected Marshaller createMarshaller() throws IOException {
+ return factory.createMarshaller(configuration);
+ }
+
+ protected Unmarshaller createUnmarshaller() throws IOException {
+ return factory.createUnmarshaller(configuration);
+ }
+
+ @Override
+ public void clear(String deploymentName) {
+ }
+
+ @Override
+ public synchronized void start(StartContext startContext) throws StartException {
+ final RiverMarshallerFactory factory = new RiverMarshallerFactory();
+ final MarshallingConfiguration configuration = new MarshallingConfiguration();
+ configuration.setClassResolver(ModularClassResolver.getInstance(moduleLoaderInjectedValue.getValue()));
+ this.configuration = configuration;
+ this.factory = factory;
+ }
+
+ @Override
+ public synchronized void stop(StopContext stopContext) {
+ }
+
+ @Override
+ public synchronized SessionPersistenceManager getValue() throws IllegalStateException, IllegalArgumentException {
+ return this;
+ }
+
+ public InjectedValue getModuleLoaderInjectedValue() {
+ return moduleLoaderInjectedValue;
+ }
+
+ protected static final class SessionEntry implements Serializable {
+ private final Date expiry;
+ private final Map data;
+
+ private SessionEntry(Date expiry, Map data) {
+ this.expiry = expiry;
+ this.data = data;
+ }
+
+ public Date getExpiry() {
+ return expiry;
+ }
+
+ public Map getData() {
+ return data;
+ }
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogAdd.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogAdd.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogAdd.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,92 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import io.undertow.predicate.Predicate;
+import io.undertow.predicate.Predicates;
+import org.jboss.as.controller.AbstractAddStepHandler;
+import org.jboss.as.controller.CapabilityServiceBuilder;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.as.controller.services.path.PathManager;
+import org.jboss.as.controller.services.path.PathManagerService;
+import org.jboss.dmr.ModelNode;
+import org.jboss.msc.service.ServiceController;
+import org.xnio.XnioWorker;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+class AccessLogAdd extends AbstractAddStepHandler {
+
+ private AccessLogAdd() {
+ super(AccessLogDefinition.ATTRIBUTES);
+ }
+
+ static final AccessLogAdd INSTANCE = new AccessLogAdd();
+
+ @Override
+ protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
+
+ final PathAddress address = context.getCurrentAddress();
+ final PathAddress hostAddress = address.getParent();
+ final PathAddress serverAddress = hostAddress.getParent();
+ final String worker = AccessLogDefinition.WORKER.resolveModelAttribute(context, model).asString();
+ final String pattern = AccessLogDefinition.PATTERN.resolveModelAttribute(context, model).asString();
+ final String directory = AccessLogDefinition.DIRECTORY.resolveModelAttribute(context, model).asString();
+ final String filePrefix = AccessLogDefinition.PREFIX.resolveModelAttribute(context, model).asString();
+ final String fileSuffix = AccessLogDefinition.SUFFIX.resolveModelAttribute(context, model).asString();
+ final boolean useServerLog = AccessLogDefinition.USE_SERVER_LOG.resolveModelAttribute(context, model).asBoolean();
+ final boolean rotate = AccessLogDefinition.ROTATE.resolveModelAttribute(context, model).asBoolean();
+ final boolean extended = AccessLogDefinition.EXTENDED.resolveModelAttribute(context, model).asBoolean();
+ final ModelNode relativeToNode = AccessLogDefinition.RELATIVE_TO.resolveModelAttribute(context, model);
+ final String relativeTo = relativeToNode.isDefined() ? relativeToNode.asString() : null;
+
+ Predicate predicate = null;
+ ModelNode predicateNode = AccessLogDefinition.PREDICATE.resolveModelAttribute(context, model);
+ if(predicateNode.isDefined()) {
+ predicate = Predicates.parse(predicateNode.asString(), getClass().getClassLoader());
+ }
+
+ final AccessLogService service;
+ if (useServerLog) {
+ service = new AccessLogService(pattern, extended, predicate);
+ } else {
+ service = new AccessLogService(pattern, directory, relativeTo, filePrefix, fileSuffix, rotate, extended, predicate);
+ }
+
+ final String serverName = serverAddress.getLastElement().getValue();
+ final String hostName = hostAddress.getLastElement().getValue();
+
+ final CapabilityServiceBuilder builder = context.getCapabilityServiceTarget().addCapability(AccessLogDefinition.ACCESS_LOG_CAPABILITY, service)
+ .addCapabilityRequirement(Capabilities.REF_IO_WORKER, XnioWorker.class, service.getWorker(), worker)
+ .addDependency(PathManagerService.SERVICE_NAME, PathManager.class, service.getPathManager())
+ .addCapabilityRequirement(Capabilities.CAPABILITY_HOST, Host.class, service.getHost(), serverName, hostName);
+ //only for backward compatibility
+ builder.addAliases(UndertowService.accessLogServiceName(serverName, hostName));
+
+ builder.setInitialMode(ServiceController.Mode.ACTIVE)
+ .install();
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,152 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.wildfly.extension.undertow;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.PersistentResourceDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.access.constraint.SensitivityClassification;
+import org.jboss.as.controller.access.management.AccessConstraintDefinition;
+import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
+import org.jboss.as.controller.capability.RuntimeCapability;
+import org.jboss.as.controller.operations.validation.StringLengthValidator;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+import org.jboss.dmr.ValueExpression;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+class AccessLogDefinition extends PersistentResourceDefinition {
+ static final RuntimeCapability ACCESS_LOG_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_ACCESS_LOG, true, AccessLogService.class)
+ .setDynamicNameMapper(path -> new String[]{
+ path.getParent().getParent().getLastElement().getValue(),
+ path.getParent().getLastElement().getValue(),
+ path.getLastElement().getValue()})
+ .build();
+
+
+ protected static final SimpleAttributeDefinition PATTERN = new SimpleAttributeDefinitionBuilder(Constants.PATTERN, ModelType.STRING, true)
+ .setDefaultValue(new ModelNode("common"))
+ .setValidator(new StringLengthValidator(1, true))
+ .setRestartAllServices()
+ .build();
+ protected static final SimpleAttributeDefinition WORKER = new SimpleAttributeDefinitionBuilder(Constants.WORKER, ModelType.STRING)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setValidator(new StringLengthValidator(1))
+ .setDefaultValue(new ModelNode("default"))
+ .setCapabilityReference(Capabilities.REF_IO_WORKER)
+ .build();
+ protected static final SimpleAttributeDefinition PREFIX = new SimpleAttributeDefinitionBuilder(Constants.PREFIX, ModelType.STRING, true)
+ .setDefaultValue(new ModelNode("access_log."))
+ .setValidator(new StringLengthValidator(1, true))
+ .setAllowExpression(true)
+ .setRestartAllServices()
+ .build();
+ protected static final SimpleAttributeDefinition SUFFIX = new SimpleAttributeDefinitionBuilder(Constants.SUFFIX, ModelType.STRING, true)
+ .setDefaultValue(new ModelNode("log"))
+ .setAllowExpression(true)
+ .setRestartAllServices()
+ .build();
+ protected static final SimpleAttributeDefinition ROTATE = new SimpleAttributeDefinitionBuilder(Constants.ROTATE, ModelType.BOOLEAN, true)
+ .setDefaultValue(new ModelNode(true))
+ .setAllowExpression(true)
+ .setRestartAllServices()
+ .build();
+ protected static final SimpleAttributeDefinition DIRECTORY = new SimpleAttributeDefinitionBuilder(Constants.DIRECTORY, ModelType.STRING)
+ .setRequired(false)
+ .setValidator(new StringLengthValidator(1, true))
+ .setDefaultValue(new ModelNode(new ValueExpression("${jboss.server.log.dir}")))
+ .setAllowExpression(true)
+ .setRestartAllServices()
+ .build();
+
+ protected static final SimpleAttributeDefinition RELATIVE_TO = new SimpleAttributeDefinitionBuilder(Constants.RELATIVE_TO, ModelType.STRING)
+ .setRequired(false)
+ .setValidator(new StringLengthValidator(1, true))
+ .setAllowExpression(true)
+ .setRestartAllServices()
+ .build();
+
+ protected static final SimpleAttributeDefinition USE_SERVER_LOG = new SimpleAttributeDefinitionBuilder(Constants.USE_SERVER_LOG, ModelType.BOOLEAN)
+ .setRequired(false)
+ .setDefaultValue(new ModelNode(false))
+ .setAllowExpression(true)
+ .setRestartAllServices()
+ .build();
+
+ protected static final SimpleAttributeDefinition EXTENDED = new SimpleAttributeDefinitionBuilder(Constants.EXTENDED, ModelType.BOOLEAN, true)
+ .setDefaultValue(new ModelNode(false))
+ .setAllowExpression(true)
+ .setRestartAllServices()
+ .build();
+
+ protected static final SimpleAttributeDefinition PREDICATE = new SimpleAttributeDefinitionBuilder(Constants.PREDICATE, ModelType.STRING, true)
+ .setAllowExpression(true)
+ .setValidator(PredicateValidator.INSTANCE)
+ .setRestartAllServices()
+ .build();
+
+ static final Collection ATTRIBUTES = Arrays.asList(
+ // IMPORTANT -- keep these in xsd order as this order controls marshalling
+ WORKER,
+ PATTERN,
+ PREFIX,
+ SUFFIX,
+ ROTATE,
+ DIRECTORY,
+ USE_SERVER_LOG,
+ RELATIVE_TO,
+ EXTENDED,
+ PREDICATE
+ );
+ static final AccessLogDefinition INSTANCE = new AccessLogDefinition();
+ private final List accessConstraints;
+
+
+ private AccessLogDefinition() {
+ super(new Parameters(UndertowExtension.PATH_ACCESS_LOG, UndertowExtension.getResolver(Constants.ACCESS_LOG))
+ .setAddHandler(AccessLogAdd.INSTANCE)
+ .setRemoveHandler(AccessLogRemove.INSTANCE)
+ .setCapabilities(ACCESS_LOG_CAPABILITY)
+ );
+ SensitivityClassification sc = new SensitivityClassification(UndertowExtension.SUBSYSTEM_NAME, "web-access-log", false, false, false);
+ this.accessConstraints = new SensitiveTargetAccessConstraintDefinition(sc).wrapAsList();
+ }
+
+ @Override
+ public List getAccessConstraints() {
+ return accessConstraints;
+ }
+
+ @Override
+ public Collection getAttributes() {
+ //noinspection unchecked
+ return (Collection) ATTRIBUTES;
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogRemove.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogRemove.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogRemove.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,52 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import org.jboss.as.controller.AbstractRemoveStepHandler;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.dmr.ModelNode;
+import org.jboss.msc.service.ServiceName;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+class AccessLogRemove extends AbstractRemoveStepHandler {
+
+ public static final AccessLogRemove INSTANCE = new AccessLogRemove();
+
+ @Override
+ protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) {
+ final PathAddress hostAddress = context.getCurrentAddress().getParent();
+ final PathAddress serverAddress = hostAddress.getParent();
+ final String hostName = hostAddress.getLastElement().getValue();
+ final String serverName = serverAddress.getLastElement().getValue();
+ final ServiceName serviceName = UndertowService.accessLogServiceName(serverName, hostName);
+ context.removeService(serviceName);
+ }
+
+ protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
+ AccessLogAdd.INSTANCE.performRuntime(context, operation, model);
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogService.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogService.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AccessLogService.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,180 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import io.undertow.attribute.ExchangeAttribute;
+import io.undertow.predicate.Predicate;
+import io.undertow.predicate.Predicates;
+import io.undertow.server.HttpHandler;
+import io.undertow.server.handlers.accesslog.AccessLogHandler;
+import io.undertow.server.handlers.accesslog.AccessLogReceiver;
+import io.undertow.server.handlers.accesslog.DefaultAccessLogReceiver;
+import io.undertow.server.handlers.accesslog.ExtendedAccessLogParser;
+import io.undertow.server.handlers.accesslog.JBossLoggingAccessLogReceiver;
+import org.jboss.as.controller.services.path.PathManager;
+import org.jboss.msc.service.Service;
+import org.jboss.msc.service.StartContext;
+import org.jboss.msc.service.StartException;
+import org.jboss.msc.service.StopContext;
+import org.jboss.msc.value.InjectedValue;
+import org.wildfly.extension.undertow.logging.UndertowLogger;
+import org.xnio.IoUtils;
+import org.xnio.XnioWorker;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+class AccessLogService implements Service {
+ private final InjectedValue host = new InjectedValue<>();
+ protected final InjectedValue worker = new InjectedValue<>();
+ private final String pattern;
+ private final String path;
+ private final String pathRelativeTo;
+ private final String filePrefix;
+ private final String fileSuffix;
+ private final boolean rotate;
+ private final boolean useServerLog;
+ private final boolean extended;
+ private final Predicate predicate;
+ private volatile AccessLogReceiver logReceiver;
+
+
+ private PathManager.Callback.Handle callbackHandle;
+
+ private Path directory;
+ private ExchangeAttribute extendedPattern;
+
+ private final InjectedValue pathManager = new InjectedValue();
+
+
+ AccessLogService(String pattern, boolean extended, Predicate predicate) {
+ this.pattern = pattern;
+ this.extended = extended;
+ this.path = null;
+ this.pathRelativeTo = null;
+ this.filePrefix = null;
+ this.fileSuffix = null;
+ this.useServerLog = true;
+ this.rotate = false; //doesn't really matter
+ this.predicate = predicate == null ? Predicates.truePredicate() : predicate;
+ }
+
+ AccessLogService(String pattern, String path, String pathRelativeTo, String filePrefix, String fileSuffix, boolean rotate, boolean extended, Predicate predicate) {
+ this.pattern = pattern;
+ this.path = path;
+ this.pathRelativeTo = pathRelativeTo;
+ this.filePrefix = filePrefix;
+ this.fileSuffix = fileSuffix;
+ this.rotate = rotate;
+ this.extended = extended;
+ this.useServerLog = false;
+ this.predicate = predicate == null ? Predicates.truePredicate() : predicate;
+ }
+
+ @Override
+ public void start(StartContext context) throws StartException {
+ if (useServerLog) {
+ logReceiver = new JBossLoggingAccessLogReceiver();
+ } else {
+ if (pathRelativeTo != null) {
+ callbackHandle = pathManager.getValue().registerCallback(pathRelativeTo, PathManager.ReloadServerCallback.create(), PathManager.Event.UPDATED, PathManager.Event.REMOVED);
+ }
+ directory = Paths.get(pathManager.getValue().resolveRelativePathEntry(path, pathRelativeTo));
+ if (!Files.exists(directory)) {
+ try {
+ Files.createDirectories(directory);
+ } catch (IOException e) {
+ throw UndertowLogger.ROOT_LOGGER.couldNotCreateLogDirectory(directory, e);
+ }
+ }
+ try {
+ DefaultAccessLogReceiver.Builder builder = DefaultAccessLogReceiver.builder().setLogWriteExecutor(worker.getValue())
+ .setOutputDirectory(directory)
+ .setLogBaseName(filePrefix)
+ .setLogNameSuffix(fileSuffix)
+ .setRotate(rotate);
+ if(extended) {
+ builder.setLogFileHeaderGenerator(new ExtendedAccessLogParser.ExtendedAccessLogHeaderGenerator(pattern));
+ extendedPattern = new ExtendedAccessLogParser(getClass().getClassLoader()).parse(pattern);
+ } else {
+ extendedPattern = null;
+ }
+ logReceiver = builder.build();
+ } catch (IllegalStateException e) {
+ throw new StartException(e);
+ }
+ }
+ host.getValue().setAccessLogService(this);
+ }
+
+ @Override
+ public void stop(StopContext context) {
+ host.getValue().setAccessLogService(null);
+ if (callbackHandle != null) {
+ callbackHandle.remove();
+ callbackHandle = null;
+ }
+ if( logReceiver instanceof DefaultAccessLogReceiver ) {
+ IoUtils.safeClose((DefaultAccessLogReceiver) logReceiver);
+ }
+ logReceiver = null;
+ }
+
+ @Override
+ public AccessLogService getValue() throws IllegalStateException, IllegalArgumentException {
+ return this;
+ }
+
+ InjectedValue getWorker() {
+ return worker;
+ }
+
+ InjectedValue getPathManager() {
+ return pathManager;
+ }
+
+ protected AccessLogHandler configureAccessLogHandler(HttpHandler handler) {
+ if(extendedPattern != null) {
+ return new AccessLogHandler(handler, logReceiver, pattern, extendedPattern, predicate);
+ } else {
+ return new AccessLogHandler(handler, logReceiver, pattern, getClass().getClassLoader(), predicate);
+ }
+ }
+
+ public InjectedValue getHost() {
+ return host;
+ }
+
+ boolean isRotate() {
+ return rotate;
+ }
+
+ String getPath() {
+ return path;
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerAdd.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerAdd.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerAdd.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,62 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import static org.wildfly.extension.undertow.Capabilities.REF_SOCKET_BINDING;
+
+import org.jboss.as.controller.CapabilityServiceBuilder;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.network.SocketBinding;
+import org.jboss.dmr.ModelNode;
+import org.xnio.OptionMap;
+
+/**
+ * @author Tomaz Cerar (c) 2012 Red Hat Inc.
+ */
+class AjpListenerAdd extends ListenerAdd {
+
+ AjpListenerAdd(AjpListenerResourceDefinition def) {
+ super(def);
+ }
+
+ @Override
+ ListenerService createService(String name, final String serverName, final OperationContext context, ModelNode model, OptionMap listenerOptions, OptionMap socketOptions) throws OperationFailedException {
+ ModelNode schemeNode = AjpListenerResourceDefinition.SCHEME.resolveModelAttribute(context, model);
+ String scheme = null;
+ if (schemeNode.isDefined()) {
+ scheme = schemeNode.asString();
+ }
+ OptionMap.Builder listenerBuilder = OptionMap.builder().addAll(listenerOptions);
+ AjpListenerResourceDefinition.MAX_AJP_PACKET_SIZE.resolveOption(context, model,listenerBuilder);
+ return new AjpListenerService(name, scheme, listenerBuilder.getMap(), socketOptions);
+ }
+
+ @Override
+ void configureAdditionalDependencies(OperationContext context, CapabilityServiceBuilder extends UndertowListener> serviceBuilder, ModelNode model, ListenerService service) throws OperationFailedException {
+ ModelNode redirectBindingRef = ListenerResourceDefinition.REDIRECT_SOCKET.resolveModelAttribute(context, model);
+ if (redirectBindingRef.isDefined()) {
+ serviceBuilder.addCapabilityRequirement(REF_SOCKET_BINDING, SocketBinding.class, service.getRedirectSocket(), redirectBindingRef.asString());
+ }
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerResourceDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerResourceDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerResourceDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,81 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import io.undertow.UndertowOptions;
+import io.undertow.protocols.ajp.AjpClientRequestClientStreamSinkChannel;
+
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.client.helpers.MeasurementUnit;
+import org.jboss.as.controller.operations.validation.IntRangeValidator;
+import org.jboss.as.controller.registry.AttributeAccess;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+import org.wildfly.extension.io.OptionAttributeDefinition;
+
+/**
+ * @author Tomaz Cerar (c) 2012 Red Hat Inc.
+ */
+public class AjpListenerResourceDefinition extends ListenerResourceDefinition {
+ protected static final AjpListenerResourceDefinition INSTANCE = new AjpListenerResourceDefinition();
+
+ protected static final SimpleAttributeDefinition SCHEME = new SimpleAttributeDefinitionBuilder(Constants.SCHEME, ModelType.STRING)
+ .setRequired(false)
+ .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
+ .setAllowExpression(true)
+ .build();
+ public static final OptionAttributeDefinition MAX_AJP_PACKET_SIZE = OptionAttributeDefinition
+ .builder("max-ajp-packet-size", UndertowOptions.MAX_AJP_PACKET_SIZE)
+ .setMeasurementUnit(MeasurementUnit.BYTES)
+ .setRequired(false)
+ .setAllowExpression(true)
+ .setDefaultValue(new ModelNode(AjpClientRequestClientStreamSinkChannel.DEFAULT_MAX_DATA_SIZE))
+ .setValidator(new IntRangeValidator(1))
+ .build();
+
+ private AjpListenerResourceDefinition() {
+ super(UndertowExtension.AJP_LISTENER_PATH);
+ }
+
+ @Override
+ protected ListenerAdd getAddHandler() {
+ return new AjpListenerAdd(this);
+ }
+
+
+ public Collection getAttributes() {
+ List attrs = new ArrayList<>(super.getAttributes());
+ attrs.add(SCHEME);
+ attrs.add(REDIRECT_SOCKET);
+ attrs.add(MAX_AJP_PACKET_SIZE);
+ return attrs;
+ }
+
+
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerService.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerService.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/AjpListenerService.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,103 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+
+import io.undertow.UndertowOptions;
+import io.undertow.server.OpenListener;
+import io.undertow.server.protocol.ajp.AjpOpenListener;
+
+import org.jboss.as.network.NetworkUtils;
+import org.jboss.msc.service.StartContext;
+import org.wildfly.extension.undertow.logging.UndertowLogger;
+import org.xnio.ChannelListener;
+import org.xnio.IoUtils;
+import org.xnio.OptionMap;
+import org.xnio.StreamConnection;
+import org.xnio.XnioWorker;
+import org.xnio.channels.AcceptingChannel;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+public class AjpListenerService extends ListenerService {
+
+ private volatile AcceptingChannel server;
+ private final String scheme;
+
+ public AjpListenerService(String name, final String scheme, OptionMap listenerOptions, OptionMap socketOptions) {
+ super(name, listenerOptions, socketOptions, false);
+ this.scheme = scheme;
+ }
+
+ @Override
+ protected OpenListener createOpenListener() {
+ AjpOpenListener ajpOpenListener = new AjpOpenListener(getBufferPool().getValue(), OptionMap.builder().addAll(commonOptions).addAll(listenerOptions).set(UndertowOptions.ENABLE_CONNECTOR_STATISTICS, getUndertowService().isStatisticsEnabled()).getMap());
+ ajpOpenListener.setScheme(scheme);
+ return ajpOpenListener;
+ }
+
+ @Override
+ void startListening(XnioWorker worker, InetSocketAddress socketAddress, ChannelListener> acceptListener) throws IOException {
+ server = worker.createStreamConnectionServer(socketAddress, acceptListener, OptionMap.builder().addAll(commonOptions).addAll(socketOptions).getMap());
+ server.resumeAccepts();
+ final InetSocketAddress boundAddress = server.getLocalAddress(InetSocketAddress.class);
+ UndertowLogger.ROOT_LOGGER.listenerStarted("AJP", getName(), NetworkUtils.formatIPAddressForURI(boundAddress.getAddress()), boundAddress.getPort());
+ }
+
+ @Override
+ protected void cleanFailedStart() {
+ //noting to do
+ }
+
+ @Override
+ void stopListening() {
+ final InetSocketAddress boundAddress = server.getLocalAddress(InetSocketAddress.class);
+ server.suspendAccepts();
+ UndertowLogger.ROOT_LOGGER.listenerSuspend("AJP", getName());
+ IoUtils.safeClose(server);
+ UndertowLogger.ROOT_LOGGER.listenerStopped("AJP", getName(), NetworkUtils.formatIPAddressForURI(boundAddress.getAddress()), boundAddress.getPort());
+ }
+
+ @Override
+ public AjpListenerService getValue() throws IllegalStateException, IllegalArgumentException {
+ return this;
+ }
+
+ @Override
+ public boolean isSecure() {
+ return scheme != null && scheme.equals("https");
+ }
+
+ @Override
+ protected void preStart(final StartContext context) {
+
+ }
+
+ @Override
+ public String getProtocol() {
+ return "ajp";
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/ApplicationSecurityDomainDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/ApplicationSecurityDomainDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/ApplicationSecurityDomainDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,493 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import static java.security.AccessController.doPrivileged;
+import static org.wildfly.extension.undertow.Capabilities.CAPABILITY_APPLICATION_SECURITY_DOMAIN;
+import static org.wildfly.extension.undertow.Capabilities.CAPABILITY_APPLICATION_SECURITY_DOMAIN_KNOWN_DEPLOYMENTS;
+import static org.wildfly.extension.undertow.Capabilities.REF_HTTP_AUTHENTICATION_FACTORY;
+import static org.wildfly.extension.undertow.Capabilities.REF_JACC_POLICY;
+
+import static org.wildfly.extension.undertow.Capabilities.REF_SECURITY_DOMAIN;
+import static org.wildfly.security.http.HttpConstants.BASIC_NAME;
+import static org.wildfly.security.http.HttpConstants.CLIENT_CERT_NAME;
+import static org.wildfly.security.http.HttpConstants.DIGEST_NAME;
+import static org.wildfly.security.http.HttpConstants.FORM_NAME;
+
+import java.security.Policy;
+import java.security.PrivilegedAction;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.BiFunction;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.function.Predicate;
+import java.util.function.Supplier;
+import java.util.function.UnaryOperator;
+
+import org.jboss.as.clustering.controller.SimpleCapabilityServiceConfigurator;
+import org.jboss.as.controller.AbstractAddStepHandler;
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.CapabilityServiceTarget;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationContext.AttachmentKey;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.OperationStepHandler;
+import org.jboss.as.controller.PersistentResourceDefinition;
+import org.jboss.as.controller.ResourceDefinition;
+import org.jboss.as.controller.ServiceRemoveStepHandler;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.StringListAttributeDefinition;
+import org.jboss.as.controller.access.constraint.ApplicationTypeConfig;
+import org.jboss.as.controller.access.constraint.SensitivityClassification;
+import org.jboss.as.controller.access.management.ApplicationTypeAccessConstraintDefinition;
+import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
+import org.jboss.as.controller.capability.RuntimeCapability;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+import org.jboss.as.controller.registry.Resource;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+import org.jboss.metadata.javaee.jboss.RunAsIdentityMetaData;
+import org.jboss.msc.Service;
+import org.jboss.msc.service.ServiceBuilder;
+import org.jboss.msc.service.ServiceController;
+import org.jboss.msc.service.ServiceController.Mode;
+import org.jboss.msc.service.ServiceName;
+import org.jboss.msc.service.StartContext;
+import org.jboss.msc.service.StartException;
+import org.jboss.msc.service.StopContext;
+import org.wildfly.clustering.service.ServiceConfigurator;
+import org.wildfly.elytron.web.undertow.server.servlet.AuthenticationManager;
+import org.wildfly.extension.undertow.security.jacc.JACCAuthorizationManager;
+import org.wildfly.extension.undertow.security.sso.DistributableSecurityDomainSingleSignOnManagerServiceConfiguratorProvider;
+import org.wildfly.security.auth.server.HttpAuthenticationFactory;
+
+import org.wildfly.security.auth.server.MechanismConfiguration;
+import org.wildfly.security.auth.server.MechanismConfigurationSelector;
+import org.wildfly.security.auth.server.MechanismRealmConfiguration;
+import org.wildfly.security.auth.server.SecurityDomain;
+import org.wildfly.security.http.HttpServerAuthenticationMechanismFactory;
+import org.wildfly.security.http.impl.ServerMechanismFactoryImpl;
+import org.wildfly.security.http.util.FilterServerMechanismFactory;
+import org.wildfly.security.http.util.sso.DefaultSingleSignOnManager;
+import org.wildfly.security.http.util.sso.SingleSignOnServerMechanismFactory;
+import org.wildfly.security.http.util.sso.SingleSignOnServerMechanismFactory.SingleSignOnConfiguration;
+import org.wildfly.security.http.util.sso.SingleSignOnSessionFactory;
+import org.wildfly.security.manager.WildFlySecurityManager;
+
+import io.undertow.server.session.SecureRandomSessionIdGenerator;
+import io.undertow.server.session.SessionIdGenerator;
+import io.undertow.servlet.api.DeploymentInfo;
+import io.undertow.servlet.api.LoginConfig;
+
+/**
+ * A {@link ResourceDefinition} to define the mapping from a security domain as specified in a web application
+ * to an {@link HttpAuthenticationFactory} plus additional policy information.
+ *
+ * @author Darran Lofthouse
+ */
+public class ApplicationSecurityDomainDefinition extends PersistentResourceDefinition {
+
+ private static Predicate SERVLET_MECHANISM;
+
+ static {
+ Set defaultMechanisms = new HashSet<>(4);
+ defaultMechanisms.add(BASIC_NAME);
+ defaultMechanisms.add(CLIENT_CERT_NAME);
+ defaultMechanisms.add(DIGEST_NAME);
+ defaultMechanisms.add(FORM_NAME);
+
+ SERVLET_MECHANISM = defaultMechanisms::contains;
+ }
+
+ static final RuntimeCapability APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY = RuntimeCapability
+ .Builder.of(CAPABILITY_APPLICATION_SECURITY_DOMAIN, true, BiFunction.class)
+ .build();
+
+ static final RuntimeCapability APPLICATION_SECURITY_DOMAIN_KNOWN_DEPLOYMENTS_CAPABILITY = RuntimeCapability
+ .Builder.of(CAPABILITY_APPLICATION_SECURITY_DOMAIN_KNOWN_DEPLOYMENTS, true)
+ .build();
+
+ static final SimpleAttributeDefinition HTTP_AUTHENTICATION_FACTORY = new SimpleAttributeDefinitionBuilder(Constants.HTTP_AUTHENITCATION_FACTORY, ModelType.STRING, false)
+ .setMinSize(1)
+ .setRestartAllServices()
+ .setCapabilityReference(REF_HTTP_AUTHENTICATION_FACTORY)
+ .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.AUTHENTICATION_FACTORY_REF)
+ .setAlternatives(Constants.SECURITY_DOMAIN)
+ .build();
+
+ static final SimpleAttributeDefinition OVERRIDE_DEPLOYMENT_CONFIG = new SimpleAttributeDefinitionBuilder(Constants.OVERRIDE_DEPLOYMENT_CONFIG, ModelType.BOOLEAN, true)
+ .setDefaultValue(new ModelNode(false))
+ .setRestartAllServices()
+ .setRequires(Constants.HTTP_AUTHENITCATION_FACTORY)
+ .build();
+
+ static final SimpleAttributeDefinition SECURITY_DOMAIN = new SimpleAttributeDefinitionBuilder(Constants.SECURITY_DOMAIN, ModelType.STRING, false)
+ .setMinSize(1)
+ .setRestartAllServices()
+ .setCapabilityReference(REF_SECURITY_DOMAIN)
+ .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.ELYTRON_SECURITY_DOMAIN_REF)
+ .setAlternatives(Constants.HTTP_AUTHENITCATION_FACTORY)
+ .build();
+
+ private static final StringListAttributeDefinition REFERENCING_DEPLOYMENTS = new StringListAttributeDefinition.Builder(Constants.REFERENCING_DEPLOYMENTS)
+ .setStorageRuntime()
+ .build();
+
+ static final SimpleAttributeDefinition ENABLE_JACC = new SimpleAttributeDefinitionBuilder(Constants.ENABLE_JACC, ModelType.BOOLEAN, true)
+ .setDefaultValue(new ModelNode(false))
+ .setMinSize(1)
+ .setRestartAllServices()
+ .build();
+
+ private static final AttributeDefinition[] ATTRIBUTES = new AttributeDefinition[] { SECURITY_DOMAIN, HTTP_AUTHENTICATION_FACTORY, OVERRIDE_DEPLOYMENT_CONFIG, ENABLE_JACC };
+
+ static final ApplicationSecurityDomainDefinition INSTANCE = new ApplicationSecurityDomainDefinition();
+
+ private static final Set knownApplicationSecurityDomains = Collections.synchronizedSet(new HashSet<>());
+
+ private static final AttachmentKey KNOWN_DEPLOYMENTS_KEY = AttachmentKey.create(KnownDeploymentsApi.class);
+
+ private ApplicationSecurityDomainDefinition() {
+ this((Parameters) new Parameters(UndertowExtension.PATH_APPLICATION_SECURITY_DOMAIN,
+ UndertowExtension.getResolver(Constants.APPLICATION_SECURITY_DOMAIN))
+ .setCapabilities(APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY)
+ .addAccessConstraints(new SensitiveTargetAccessConstraintDefinition(new SensitivityClassification(UndertowExtension.SUBSYSTEM_NAME, Constants.APPLICATION_SECURITY_DOMAIN, false, false, false)),
+ new ApplicationTypeAccessConstraintDefinition(new ApplicationTypeConfig(UndertowExtension.SUBSYSTEM_NAME, Constants.APPLICATION_SECURITY_DOMAIN)))
+ , new AddHandler());
+ }
+
+ private ApplicationSecurityDomainDefinition(Parameters parameters, AbstractAddStepHandler add) {
+ super(parameters.setAddHandler(add).setRemoveHandler(new RemoveHandler(add)));
+ }
+
+ @Override
+ public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
+ knownApplicationSecurityDomains.clear(); // If we are registering, time for a clean start.
+ super.registerAttributes(resourceRegistration);
+ if (resourceRegistration.getProcessType().isServer()) {
+ resourceRegistration.registerReadOnlyAttribute(REFERENCING_DEPLOYMENTS, new ReferencingDeploymentsHandler());
+ }
+ }
+
+ @Override
+ protected List extends PersistentResourceDefinition> getChildren() {
+ return Collections.singletonList(new ApplicationSecurityDomainSingleSignOnDefinition());
+ }
+
+ private static class ReferencingDeploymentsHandler implements OperationStepHandler {
+
+ @Override
+ public void execute(OperationContext context, ModelNode operation) throws OperationFailedException {
+ if (context.isDefaultRequiresRuntime()) {
+ context.addStep((ctx, op) -> {
+ final KnownDeploymentsApi knownDeploymentsApi = context.getCapabilityRuntimeAPI(
+ CAPABILITY_APPLICATION_SECURITY_DOMAIN_KNOWN_DEPLOYMENTS, ctx.getCurrentAddressValue(),
+ KnownDeploymentsApi.class);
+
+ ModelNode deploymentList = new ModelNode();
+ for (String current : knownDeploymentsApi.getKnownDeployments()) {
+ deploymentList.add(current);
+ }
+
+ context.getResult().set(deploymentList);
+ }, OperationContext.Stage.RUNTIME);
+ }
+ }
+
+ }
+
+ private static class AddHandler extends AbstractAddStepHandler {
+
+ private AddHandler() {
+ super(ATTRIBUTES);
+ }
+
+ /* (non-Javadoc)
+ * @see org.jboss.as.controller.AbstractAddStepHandler#populateModel(org.jboss.as.controller.OperationContext, org.jboss.dmr.ModelNode, org.jboss.as.controller.registry.Resource)
+ */
+ @Override
+ protected void populateModel(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
+ super.populateModel(context, operation, resource);
+ knownApplicationSecurityDomains.add(context.getCurrentAddressValue());
+ }
+
+ @Override
+ protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
+ super.recordCapabilitiesAndRequirements(context, operation, resource);
+ KnownDeploymentsApi knownDeployments = new KnownDeploymentsApi();
+ context.registerCapability(RuntimeCapability.Builder
+ .of(CAPABILITY_APPLICATION_SECURITY_DOMAIN_KNOWN_DEPLOYMENTS, true, knownDeployments).build()
+ .fromBaseCapability(context.getCurrentAddressValue()));
+ context.attach(KNOWN_DEPLOYMENTS_KEY, knownDeployments);
+ }
+
+ @Override
+ protected void performRuntime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
+ ModelNode model = resource.getModel();
+ CapabilityServiceTarget target = context.getCapabilityServiceTarget();
+
+ final String securityDomain = SECURITY_DOMAIN.resolveModelAttribute(context, model).asStringOrNull();
+ final String httpServerMechanismFactory = HTTP_AUTHENTICATION_FACTORY.resolveModelAttribute(context, model).asStringOrNull();
+ boolean overrideDeploymentConfig = OVERRIDE_DEPLOYMENT_CONFIG.resolveModelAttribute(context, model).asBoolean();
+ boolean enableJacc = ENABLE_JACC.resolveModelAttribute(context, model).asBoolean();
+
+ String securityDomainName = context.getCurrentAddressValue();
+
+ ServiceName applicationSecurityDomainName = APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY.getCapabilityServiceName(context.getCurrentAddress());
+
+ ServiceBuilder> serviceBuilder = target
+ .addService(applicationSecurityDomainName)
+ .setInitialMode(Mode.LAZY);
+
+ final Function factoryFunction;
+ if (httpServerMechanismFactory != null) {
+ Supplier httpAuthenticationFactorySupplier = serviceBuilder.requires(context.getCapabilityServiceName(REF_HTTP_AUTHENTICATION_FACTORY, HttpAuthenticationFactory.class, httpServerMechanismFactory));
+ factoryFunction = (s) -> httpAuthenticationFactorySupplier.get();
+ } else {
+ Supplier securityDomainSupplier = serviceBuilder.requires(context.getCapabilityServiceName(REF_SECURITY_DOMAIN, SecurityDomain.class, securityDomain));
+ factoryFunction = toHttpAuthenticationFactoryFunction(securityDomainSupplier);
+ }
+
+ if (enableJacc) {
+ serviceBuilder.requires(context.getCapabilityServiceName(REF_JACC_POLICY, Policy.class));
+ }
+
+ final Supplier> transformerSupplier;
+ if (resource.hasChild(UndertowExtension.PATH_SSO)) {
+ ModelNode ssoModel = resource.getChild(UndertowExtension.PATH_SSO).getModel();
+
+ String cookieName = SingleSignOnDefinition.Attribute.COOKIE_NAME.resolveModelAttribute(context, ssoModel).asString();
+ String domain = SingleSignOnDefinition.Attribute.DOMAIN.resolveModelAttribute(context, ssoModel).asString();
+ String path = SingleSignOnDefinition.Attribute.PATH.resolveModelAttribute(context, ssoModel).asString();
+ boolean httpOnly = SingleSignOnDefinition.Attribute.HTTP_ONLY.resolveModelAttribute(context, ssoModel).asBoolean();
+ boolean secure = SingleSignOnDefinition.Attribute.SECURE.resolveModelAttribute(context, ssoModel).asBoolean();
+ SingleSignOnConfiguration singleSignOnConfiguration = new SingleSignOnConfiguration(cookieName, domain, path, httpOnly, secure);
+
+ ServiceName managerServiceName = new SingleSignOnManagerServiceNameProvider(securityDomainName).getServiceName();
+ SessionIdGenerator generator = new SecureRandomSessionIdGenerator();
+
+ DistributableSecurityDomainSingleSignOnManagerServiceConfiguratorProvider.INSTANCE
+ .map(provider -> provider.getServiceConfigurator(managerServiceName, securityDomainName, generator))
+ .orElse(new SimpleCapabilityServiceConfigurator<>(managerServiceName, new DefaultSingleSignOnManager(new ConcurrentHashMap<>(), generator::createSessionId)))
+ .configure(context).build(target).setInitialMode(ServiceController.Mode.ON_DEMAND).install();
+
+ ServiceConfigurator factoryConfigurator = new SingleSignOnSessionFactoryServiceConfigurator(securityDomainName).configure(context, ssoModel);
+ factoryConfigurator.build(target).setInitialMode(ServiceController.Mode.ON_DEMAND).install();
+
+ Supplier singleSignOnSessionFactorySupplier = serviceBuilder.requires(factoryConfigurator.getServiceName());
+ UnaryOperator transformer = (factory) -> new SingleSignOnServerMechanismFactory(factory, singleSignOnSessionFactorySupplier.get(), singleSignOnConfiguration);
+ transformerSupplier = () -> transformer;
+
+ } else {
+ transformerSupplier = () -> null;
+ }
+
+ Consumer, Registration>> valueConsumer = serviceBuilder.provides(applicationSecurityDomainName);
+ ApplicationSecurityDomainService service = new ApplicationSecurityDomainService(overrideDeploymentConfig, enableJacc, factoryFunction, transformerSupplier, valueConsumer);
+ serviceBuilder.setInstance(service);
+ serviceBuilder.install();
+
+ KnownDeploymentsApi knownDeploymentsApi = context.getAttachment(KNOWN_DEPLOYMENTS_KEY);
+ knownDeploymentsApi.setApplicationSecurityDomainService(service);
+ }
+
+ }
+
+ private static Function toHttpAuthenticationFactoryFunction(final Supplier securityDomainSupplier) {
+ final HttpServerAuthenticationMechanismFactory mechanismFactory = new FilterServerMechanismFactory(new ServerMechanismFactoryImpl(), SERVLET_MECHANISM);
+ return (realmName) -> HttpAuthenticationFactory.builder().setFactory(mechanismFactory)
+ .setSecurityDomain(securityDomainSupplier.get())
+ .setMechanismConfigurationSelector(
+ MechanismConfigurationSelector.constantSelector(realmName == null ? MechanismConfiguration.EMPTY
+ : MechanismConfiguration.builder()
+ .addMechanismRealm(
+ MechanismRealmConfiguration.builder().setRealmName(realmName).build())
+ .build()))
+ .build();
+ }
+
+ private static class RemoveHandler extends ServiceRemoveStepHandler {
+
+ /**
+ * @param addOperation
+ */
+ protected RemoveHandler(AbstractAddStepHandler addOperation) {
+ super(addOperation, APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY, APPLICATION_SECURITY_DOMAIN_KNOWN_DEPLOYMENTS_CAPABILITY);
+ }
+
+ @Override
+ protected void performRemove(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
+ super.performRemove(context, operation, model);
+ knownApplicationSecurityDomains.remove(context.getCurrentAddressValue());
+ }
+
+ @Override
+ protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) {
+ super.performRuntime(context, operation, model);
+ if (context.isResourceServiceRestartAllowed()) {
+ final String securityDomainName = context.getCurrentAddressValue();
+ context.removeService(new SingleSignOnManagerServiceNameProvider(securityDomainName).getServiceName());
+ context.removeService(new SingleSignOnSessionFactoryServiceNameProvider(securityDomainName).getServiceName());
+ }
+ }
+
+ @Override
+ protected ServiceName serviceName(String name) {
+ RuntimeCapability> dynamicCapability = APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY.fromBaseCapability(name);
+ return dynamicCapability.getCapabilityServiceName(BiFunction.class); // no-arg getCapabilityServiceName() would be fine too
+ }
+
+ }
+
+ @Override
+ public Collection getAttributes() {
+ return Arrays.asList(ATTRIBUTES);
+ }
+
+ Predicate getKnownSecurityDomainPredicate() {
+ return knownApplicationSecurityDomains::contains;
+ }
+
+ private static class ApplicationSecurityDomainService implements Service, BiFunction, Registration> {
+
+ private final Function factoryFunction;
+ private final Supplier> singleSignOnTransformerSupplier;
+
+ private final Consumer, Registration>> valueConsumer;
+
+ private final boolean overrideDeploymentConfig;
+ private final Set registrations = new HashSet<>();
+ private final boolean enableJacc;
+
+ private ApplicationSecurityDomainService(final boolean overrideDeploymentConfig, boolean enableJacc, Function factoryFunction, Supplier> singleSignOnTransformerSupplier, Consumer, Registration>> valueConsumer) {
+ this.overrideDeploymentConfig = overrideDeploymentConfig;
+ this.enableJacc = enableJacc;
+ this.factoryFunction = factoryFunction;
+ this.singleSignOnTransformerSupplier = singleSignOnTransformerSupplier;
+ this.valueConsumer = valueConsumer;
+ }
+
+ @Override
+ public void start(StartContext context) throws StartException {
+ valueConsumer.accept(this);
+ }
+
+ @Override
+ public void stop(StopContext context) {}
+
+ @Override
+ public Registration apply(DeploymentInfo deploymentInfo, Function runAsMapper) {
+ AuthenticationManager.Builder builder = AuthenticationManager.builder()
+ .setHttpAuthenticationFactory(factoryFunction.apply(getRealmName(deploymentInfo)))
+ .setOverrideDeploymentConfig(overrideDeploymentConfig)
+ .setHttpAuthenticationFactoryTransformer(singleSignOnTransformerSupplier.get())
+ .setRunAsMapper(runAsMapper);
+
+ if (enableJacc) {
+ builder.setAuthorizationManager(JACCAuthorizationManager.INSTANCE);
+ }
+
+ AuthenticationManager authenticationManager = builder.build();
+ authenticationManager.configure(deploymentInfo);
+
+ RegistrationImpl registration = new RegistrationImpl(deploymentInfo);
+ synchronized(registrations) {
+ registrations.add(registration);
+ }
+ return registration;
+ }
+
+ private String getRealmName(final DeploymentInfo deploymentInfo) {
+ LoginConfig loginConfig = deploymentInfo.getLoginConfig();
+ return loginConfig != null ? loginConfig.getRealmName() : null;
+ }
+
+ private List getDeployments() {
+ synchronized (registrations) {
+ List deployments = new ArrayList<>(registrations.size());
+ for (RegistrationImpl registration : registrations) {
+ deployments.add(registration.deploymentInfo.getDeploymentName());
+ }
+ return deployments;
+ }
+ }
+
+ private class RegistrationImpl implements Registration {
+
+ final DeploymentInfo deploymentInfo;
+
+ private RegistrationImpl(DeploymentInfo deploymentInfo) {
+ this.deploymentInfo = deploymentInfo;
+ }
+
+ @Override
+ public void cancel() {
+ if (WildFlySecurityManager.isChecking()) {
+ doPrivileged((PrivilegedAction) () -> {
+ SecurityDomain.unregisterClassLoader(deploymentInfo.getClassLoader());
+ return null;
+ });
+ } else {
+ SecurityDomain.unregisterClassLoader(deploymentInfo.getClassLoader());
+ }
+ synchronized(registrations) {
+ registrations.remove(this);
+ }
+ }
+
+ }
+
+ }
+
+ public interface Registration {
+
+ /**
+ * Cancel the registration.
+ */
+ void cancel();
+
+ }
+
+ private static class KnownDeploymentsApi {
+
+ private volatile ApplicationSecurityDomainService service;
+
+ List getKnownDeployments() {
+ return service != null ? service.getDeployments() : Collections.emptyList();
+
+ }
+
+ void setApplicationSecurityDomainService(final ApplicationSecurityDomainService service) {
+ this.service = service;
+ }
+ }
+
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/ApplicationSecurityDomainSingleSignOnDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/ApplicationSecurityDomainSingleSignOnDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/ApplicationSecurityDomainSingleSignOnDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,93 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.util.function.UnaryOperator;
+
+import org.jboss.as.clustering.controller.CapabilityReference;
+import org.jboss.as.clustering.controller.CommonUnaryRequirement;
+import org.jboss.as.clustering.controller.UnaryCapabilityNameResolver;
+import org.jboss.as.clustering.controller.ReloadRequiredResourceRegistration;
+import org.jboss.as.clustering.controller.ResourceDescriptor;
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
+import org.jboss.as.controller.capability.RuntimeCapability;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+import org.jboss.as.controller.security.CredentialReference;
+import org.jboss.dmr.ModelType;
+
+/**
+ * @author Paul Ferraro
+ */
+public class ApplicationSecurityDomainSingleSignOnDefinition extends SingleSignOnDefinition {
+
+ enum Capability implements org.jboss.as.clustering.controller.Capability {
+ SSO_CREDENTIAL_STORE("org.wildfly.extension.undertow.application-security-domain.single-sign-on.credential-store"),
+ SSO_KEY_STORE("org.wildfly.extension.undertow.application-security-domain.single-sign-on.key-store"),
+ SSO_SSL_CONTEXT("org.wildfly.extension.undertow.application-security-domain.single-sign-on.client-ssl-context"),
+ ;
+ private final RuntimeCapability definition;
+
+ Capability(String name) {
+ this.definition = RuntimeCapability.Builder.of(name, true).setDynamicNameMapper(UnaryCapabilityNameResolver.PARENT).build();
+ }
+
+ @Override
+ public RuntimeCapability getDefinition() {
+ return this.definition;
+ }
+ }
+
+ enum Attribute implements org.jboss.as.clustering.controller.Attribute {
+ CREDENTIAL(CredentialReference.getAttributeBuilder(CredentialReference.CREDENTIAL_REFERENCE, CredentialReference.CREDENTIAL_REFERENCE, false, new CapabilityReference(Capability.SSO_CREDENTIAL_STORE, CommonUnaryRequirement.CREDENTIAL_STORE)).setAccessConstraints(SensitiveTargetAccessConstraintDefinition.CREDENTIAL).build()),
+ KEY_ALIAS("key-alias", ModelType.STRING, builder -> builder.setAllowExpression(true).addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SSL_REF)),
+ KEY_STORE("key-store", ModelType.STRING, builder -> builder.setCapabilityReference(new CapabilityReference(Capability.SSO_KEY_STORE, CommonUnaryRequirement.KEY_STORE)).addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SSL_REF)),
+ SSL_CONTEXT("client-ssl-context", ModelType.STRING, builder -> builder.setRequired(false).setCapabilityReference(new CapabilityReference(Capability.SSO_SSL_CONTEXT, CommonUnaryRequirement.SSL_CONTEXT)).setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SSL_REF)),
+ ;
+ private final AttributeDefinition definition;
+
+ Attribute(String name, ModelType type, UnaryOperator configurator) {
+ this.definition = configurator.apply(new SimpleAttributeDefinitionBuilder(name, type).setRequired(true)).build();
+ }
+
+ Attribute(AttributeDefinition definition) {
+ this.definition = definition;
+ }
+
+ @Override
+ public AttributeDefinition getDefinition() {
+ return this.definition;
+ }
+ }
+
+ @Override
+ public void registerOperations(ManagementResourceRegistration registration) {
+ ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver())
+ .addAttributes(Attribute.class)
+ .addAttributes(SingleSignOnDefinition.Attribute.class)
+ .addCapabilities(Capability.class)
+ ;
+ new ReloadRequiredResourceRegistration(descriptor).register(registration);
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheAdd.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheAdd.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheAdd.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,67 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP_ADDR;
+
+
+import org.jboss.as.controller.AbstractAddStepHandler;
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.dmr.ModelNode;
+import org.jboss.msc.service.ServiceController;
+import org.jboss.msc.service.ServiceTarget;
+
+/**
+ * @author Stuart Douglas
+ */
+final class BufferCacheAdd extends AbstractAddStepHandler {
+ static final BufferCacheAdd INSTANCE = new BufferCacheAdd();
+
+ BufferCacheAdd() {
+ }
+
+ @Override
+ protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
+ for (AttributeDefinition def : BufferCacheDefinition.INSTANCE.getAttributes()) {
+ def.validateAndSet(operation, model);
+ }
+ }
+ @Override
+ protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
+ final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR));
+ final String name = address.getLastElement().getValue();
+ int bufferSize = BufferCacheDefinition.BUFFER_SIZE.resolveModelAttribute(context, model).asInt();
+ int buffersPerRegions = BufferCacheDefinition.BUFFERS_PER_REGION.resolveModelAttribute(context, model).asInt();
+ int maxRegions = BufferCacheDefinition.MAX_REGIONS.resolveModelAttribute(context, model).asInt();
+
+ final BufferCacheService service = new BufferCacheService(bufferSize, buffersPerRegions, maxRegions);
+ final ServiceTarget target = context.getServiceTarget();
+
+ target.addService(BufferCacheService.SERVICE_NAME.append(name), service)
+ .setInitialMode(ServiceController.Mode.ON_DEMAND)
+ .install();
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,78 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.PersistentResourceDefinition;
+import org.jboss.as.controller.ServiceRemoveStepHandler;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.operations.validation.IntRangeValidator;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+public class BufferCacheDefinition extends PersistentResourceDefinition {
+ protected static final SimpleAttributeDefinition BUFFER_SIZE = new SimpleAttributeDefinitionBuilder(Constants.BUFFER_SIZE, ModelType.INT)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setValidator(new IntRangeValidator(0, false, true))
+ .setDefaultValue(new ModelNode(1024))
+ .setAllowExpression(true)
+ .build();
+ protected static final SimpleAttributeDefinition BUFFERS_PER_REGION = new SimpleAttributeDefinitionBuilder(Constants.BUFFERS_PER_REGION, ModelType.INT)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setValidator(new IntRangeValidator(0, false, true))
+ .setDefaultValue(new ModelNode(1024))
+ .setAllowExpression(true)
+ .build();
+ protected static final SimpleAttributeDefinition MAX_REGIONS = new SimpleAttributeDefinitionBuilder(Constants.MAX_REGIONS, ModelType.INT)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setValidator(new IntRangeValidator(0, false, true))
+ .setAllowExpression(true)
+ .setDefaultValue(new ModelNode(10))
+ .build();
+ static final BufferCacheDefinition INSTANCE = new BufferCacheDefinition();
+ private static final List ATTRIBUTES = Collections.unmodifiableList(Arrays.asList(BUFFER_SIZE, BUFFERS_PER_REGION, MAX_REGIONS));
+
+ private BufferCacheDefinition() {
+ super(UndertowExtension.PATH_BUFFER_CACHE,
+ UndertowExtension.getResolver(Constants.BUFFER_CACHE),
+ BufferCacheAdd.INSTANCE,
+ new ServiceRemoveStepHandler(BufferCacheService.SERVICE_NAME, BufferCacheAdd.INSTANCE));
+ }
+
+ @Override
+ public Collection getAttributes() {
+ return (Collection) ATTRIBUTES;
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheService.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheService.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/BufferCacheService.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,65 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import io.undertow.server.handlers.cache.DirectBufferCache;
+import org.jboss.msc.service.Service;
+import org.jboss.msc.service.ServiceName;
+import org.jboss.msc.service.StartContext;
+import org.jboss.msc.service.StartException;
+import org.jboss.msc.service.StopContext;
+
+/**
+ * @author Stuart Douglas
+ */
+public class BufferCacheService implements Service {
+
+ public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("undertow", "bufferCache");
+
+ private final int bufferSize;
+ private final int buffersPerRegion;
+ private final int maxRegions;
+
+ private volatile DirectBufferCache value;
+
+ public BufferCacheService(final int bufferSize, final int buffersPerRegion, final int maxRegions) {
+ this.bufferSize = bufferSize;
+ this.buffersPerRegion = buffersPerRegion;
+ this.maxRegions = maxRegions;
+ }
+
+ @Override
+ public void start(final StartContext startContext) throws StartException {
+ value = new DirectBufferCache(bufferSize, buffersPerRegion, maxRegions * buffersPerRegion * bufferSize);
+ }
+
+ @Override
+ public void stop(final StopContext stopContext) {
+ value = null;
+ }
+
+ @Override
+ public DirectBufferCache getValue() throws IllegalStateException, IllegalArgumentException {
+ return value;
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/ByteBufferPoolDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/ByteBufferPoolDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/ByteBufferPoolDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,180 @@
+package org.wildfly.extension.undertow;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+import org.jboss.as.controller.AbstractAddStepHandler;
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.PersistentResourceDefinition;
+import org.jboss.as.controller.ReloadRequiredRemoveStepHandler;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.capability.RuntimeCapability;
+import org.jboss.as.controller.operations.validation.IntRangeValidator;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+import org.jboss.msc.service.Service;
+import org.jboss.msc.service.ServiceController;
+import org.jboss.msc.service.StartContext;
+import org.jboss.msc.service.StartException;
+import org.jboss.msc.service.StopContext;
+
+import io.undertow.connector.ByteBufferPool;
+import io.undertow.server.DefaultByteBufferPool;
+
+public class ByteBufferPoolDefinition extends PersistentResourceDefinition {
+
+
+ static final RuntimeCapability UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY =
+ RuntimeCapability.Builder.of(Capabilities.CAPABILITY_BYTE_BUFFER_POOL, true, ByteBufferPool.class).build();
+
+
+ private static final int defaultBufferSize;
+ private static final boolean defaultDirectBuffers;
+
+ static {
+ long maxMemory = Runtime.getRuntime().maxMemory();
+ //smaller than 64mb of ram we use 512b buffers
+ if (maxMemory < 64 * 1024 * 1024) {
+ //use 512b buffers
+ defaultDirectBuffers = false;
+ defaultBufferSize = 512;
+ } else if (maxMemory < 128 * 1024 * 1024) {
+ //use 1k buffers
+ defaultDirectBuffers = true;
+ defaultBufferSize = 1024;
+ } else {
+ //use 16k buffers for best performance
+ //as 16k is generally the max amount of data that can be sent in a single write() call
+ defaultDirectBuffers = true;
+ defaultBufferSize = 1024 * 16;
+ }
+ }
+ protected static final SimpleAttributeDefinition BUFFER_SIZE = new SimpleAttributeDefinitionBuilder(Constants.BUFFER_SIZE, ModelType.INT)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setValidator(new IntRangeValidator(0, true, true))
+ .setAllowExpression(true)
+ .build();
+
+ protected static final SimpleAttributeDefinition MAX_POOL_SIZE = new SimpleAttributeDefinitionBuilder(Constants.MAX_POOL_SIZE, ModelType.INT)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setValidator(new IntRangeValidator(0, true, true))
+ .setAllowExpression(true)
+ .build();
+
+ protected static final SimpleAttributeDefinition DIRECT = new SimpleAttributeDefinitionBuilder(Constants.DIRECT, ModelType.BOOLEAN)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setAllowExpression(true)
+ .build();
+
+ protected static final SimpleAttributeDefinition THREAD_LOCAL_CACHE_SIZE = new SimpleAttributeDefinitionBuilder(Constants.THREAD_LOCAL_CACHE_SIZE, ModelType.INT)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setValidator(new IntRangeValidator(0, true, true))
+ .setAllowExpression(true)
+ .setDefaultValue(new ModelNode(12))
+ .build();
+
+
+ protected static final SimpleAttributeDefinition LEAK_DETECTION_PERCENT = new SimpleAttributeDefinitionBuilder(Constants.LEAK_DETECTION_PERCENT, ModelType.INT)
+ .setRequired(false)
+ .setRestartAllServices()
+ .setValidator(new IntRangeValidator(0, true, true))
+ .setAllowExpression(true)
+ .setDefaultValue(new ModelNode(0))
+ .build();
+
+ private static final List ATTRIBUTES = Arrays.asList(BUFFER_SIZE, MAX_POOL_SIZE, DIRECT, THREAD_LOCAL_CACHE_SIZE, LEAK_DETECTION_PERCENT);
+
+
+ public static final ByteBufferPoolDefinition INSTANCE = new ByteBufferPoolDefinition();
+
+ private ByteBufferPoolDefinition() {
+ super(UndertowExtension.BYTE_BUFFER_POOL_PATH,
+ UndertowExtension.getResolver(Constants.BYTE_BUFFER_POOL),
+ new BufferPoolAdd(),
+ new ReloadRequiredRemoveStepHandler()
+ );
+ }
+
+ @Override
+ public void registerCapabilities(ManagementResourceRegistration resourceRegistration) {
+ resourceRegistration.registerCapability(UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY);
+ }
+
+ @Override
+ public Collection getAttributes() {
+ return ATTRIBUTES;
+ }
+
+
+ private static class BufferPoolAdd extends AbstractAddStepHandler {
+
+ private BufferPoolAdd() {
+ super(ByteBufferPoolDefinition.ATTRIBUTES);
+ }
+
+ @Override
+ protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
+ final ModelNode bufferSizeModel = BUFFER_SIZE.resolveModelAttribute(context, model);
+ final ModelNode maxPoolSizeModel = MAX_POOL_SIZE.resolveModelAttribute(context, model);
+ final ModelNode directModel = DIRECT.resolveModelAttribute(context, model);
+ final int threadLocalCacheSize = THREAD_LOCAL_CACHE_SIZE.resolveModelAttribute(context, model).asInt();
+ final int leakDetectionPercent = LEAK_DETECTION_PERCENT.resolveModelAttribute(context, model).asInt();
+
+ final int bufferSize = bufferSizeModel.asInt(defaultBufferSize);
+ final int maxPoolSize = maxPoolSizeModel.asInt(-1);
+ final boolean direct = directModel.asBoolean(defaultDirectBuffers);
+
+ final ByteBufferPoolService service = new ByteBufferPoolService(direct, bufferSize, maxPoolSize, threadLocalCacheSize, leakDetectionPercent);
+ context.getCapabilityServiceTarget().addCapability(UNDERTOW_BUFFER_POOL_RUNTIME_CAPABILITY, service)
+ .setInitialMode(ServiceController.Mode.ACTIVE)
+ .install();
+
+ }
+ }
+
+ private static final class ByteBufferPoolService implements Service {
+
+ private final boolean direct;
+ private final int size;
+ private final int maxSize;
+ private final int threadLocalCacheSize;
+ private final int leakDetectionPercent;
+
+
+ private volatile ByteBufferPool pool;
+
+ private ByteBufferPoolService(boolean direct, int size, int maxSize, int threadLocalCacheSize, int leakDetectionPercent) {
+ this.direct = direct;
+ this.size = size;
+ this.maxSize = maxSize;
+ this.threadLocalCacheSize = threadLocalCacheSize;
+ this.leakDetectionPercent = leakDetectionPercent;
+ }
+
+
+ @Override
+ public void start(StartContext startContext) throws StartException {
+ pool = new DefaultByteBufferPool(direct, size, maxSize, threadLocalCacheSize, leakDetectionPercent);
+ }
+
+ @Override
+ public void stop(StopContext stopContext) {
+ pool.close();
+ pool = null;
+ }
+
+ @Override
+ public ByteBufferPool getValue() throws IllegalStateException, IllegalArgumentException {
+ return pool;
+ }
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/Capabilities.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/Capabilities.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/Capabilities.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,62 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+/**
+ * @author Tomaz Cerar (c) 2017 Red Hat Inc.
+ */
+public final class Capabilities {
+ /*
+ Capabilities in this subsystem
+ */
+ public static final String CAPABILITY_UNDERTOW = "org.wildfly.undertow";
+ public static final String CAPABILITY_LISTENER = "org.wildfly.undertow.listener";
+ public static final String CAPABILITY_SERVER = "org.wildfly.undertow.server";
+ public static final String CAPABILITY_HOST = "org.wildfly.undertow.host";
+ public static final String CAPABILITY_HOST_SSO = "org.wildfly.undertow.host.sso";
+ public static final String CAPABILITY_LOCATION = "org.wildfly.undertow.host.location";
+ public static final String CAPABILITY_ACCESS_LOG = "org.wildfly.undertow.host.access-log";
+ public static final String CAPABILITY_HANDLER = "org.wildfly.extension.undertow.handler";
+ public static final String CAPABILITY_MOD_CLUSTER_FILTER = "org.wildfly.undertow.mod_cluster-filter";
+ public static final String CAPABILITY_SERVLET_CONTAINER = "org.wildfly.undertow.servlet-container";
+ public static final String CAPABILITY_WEBSOCKET = "org.wildfly.undertow.servlet-container.websocket";
+ public static final String CAPABILITY_HTTP_INVOKER = "org.wildfly.undertow.http-invoker";
+ public static final String CAPABILITY_HTTP_INVOKER_HOST = "org.wildfly.undertow.http-invoker.host";
+ public static final String CAPABILITY_APPLICATION_SECURITY_DOMAIN = "org.wildfly.undertow.application-security-domain";
+ public static final String CAPABILITY_APPLICATION_SECURITY_DOMAIN_KNOWN_DEPLOYMENTS = "org.wildfly.undertow.application-security-domain.known-deployments";
+ public static final String CAPABILITY_REVERSE_PROXY_HANDLER_HOST = "org.wildfly.undertow.reverse-proxy.host";
+ public static final String CAPABILITY_BYTE_BUFFER_POOL = "org.wildfly.undertow.byte-buffer-pool";
+
+ /*
+ References to capabilities outside of the subsystem
+ */
+
+ public static final String REF_IO_WORKER = "org.wildfly.io.worker";
+ public static final String REF_SECURITY_DOMAIN = "org.wildfly.security.security-domain";
+ public static final String REF_SOCKET_BINDING = "org.wildfly.network.socket-binding";
+ public static final String REF_SSL_CONTEXT = "org.wildfly.security.ssl-context";
+ public static final String REF_HTTP_AUTHENTICATION_FACTORY = "org.wildfly.security.http-authentication-factory";
+ public static final String REF_JACC_POLICY = "org.wildfly.security.jacc-policy";
+ public static final String REF_OUTBOUND_SOCKET = "org.wildfly.network.outbound-socket-binding";
+ public static final String REF_REQUEST_CONTROLLER = "org.wildfly.request-controller";
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/ConsoleRedirectService.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/ConsoleRedirectService.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/ConsoleRedirectService.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,171 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.net.InetAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import io.undertow.server.HttpHandler;
+import io.undertow.server.HttpServerExchange;
+import io.undertow.server.handlers.RedirectHandler;
+import io.undertow.util.Headers;
+import org.jboss.as.network.NetworkInterfaceBinding;
+import org.jboss.as.server.mgmt.domain.HttpManagement;
+import org.jboss.msc.service.Service;
+import org.jboss.msc.service.StartContext;
+import org.jboss.msc.service.StartException;
+import org.jboss.msc.service.StopContext;
+import org.jboss.msc.value.InjectedValue;
+import org.wildfly.extension.undertow.logging.UndertowLogger;
+
+/**
+ * A service to setup a redirect for the web administration console.
+ *
+ * @author James R. Perkins
+ */
+class ConsoleRedirectService implements Service {
+
+ private static final String CONSOLE_PATH = "/console";
+ private static final String NO_CONSOLE = "/noconsole.html";
+ private static final String NO_REDIRECT = "/noredirect.html";
+
+ private final InjectedValue httpManagementInjector = new InjectedValue<>();
+ private final InjectedValue hostInjector = new InjectedValue<>();
+
+ @Override
+ public void start(final StartContext startContext) throws StartException {
+ final Host host = hostInjector.getValue();
+ UndertowLogger.ROOT_LOGGER.debugf("Starting console redirect for %s", host.getName());
+ final HttpManagement httpManagement = httpManagementInjector.getOptionalValue();
+ if (httpManagement != null) {
+ if (httpManagement.hasConsole()) {
+ host.registerHandler(CONSOLE_PATH, new ConsoleRedirectHandler(httpManagement));
+ } else {
+ host.registerHandler(CONSOLE_PATH, new RedirectHandler(NO_CONSOLE));
+ }
+ } else {
+ host.registerHandler(CONSOLE_PATH, new RedirectHandler(NO_CONSOLE));
+ }
+ }
+
+ @Override
+ public void stop(final StopContext stopContext) {
+ final Host host = hostInjector.getValue();
+ UndertowLogger.ROOT_LOGGER.debugf("Stopping console redirect for %s", host.getName());
+ host.unregisterHandler(CONSOLE_PATH);
+ }
+
+ @Override
+ public ConsoleRedirectService getValue() throws IllegalStateException, IllegalArgumentException {
+ return this;
+ }
+
+ protected InjectedValue getHttpManagementInjector() {
+ return httpManagementInjector;
+ }
+
+ protected InjectedValue getHostInjector() {
+ return hostInjector;
+ }
+
+ private static class ConsoleRedirectHandler implements HttpHandler {
+ private static final int DEFAULT_PORT = 80;
+ private static final String HTTP = "http";
+ private static final String HTTPS = "https";
+ private static final int SECURE_DEFAULT_PORT = 443;
+
+ private final int port;
+ private final int securePort;
+ private final NetworkInterfaceBinding networkInterfaceBinding;
+ private final NetworkInterfaceBinding secureNetworkInterfaceBinding;
+
+ ConsoleRedirectHandler(final HttpManagement httpManagement) {
+ port = httpManagement.getHttpPort();
+ securePort = httpManagement.getHttpsPort();
+ networkInterfaceBinding = httpManagement.getHttpNetworkInterfaceBinding();
+ secureNetworkInterfaceBinding = httpManagement.getHttpsNetworkInterfaceBinding();
+ }
+
+ @Override
+ public void handleRequest(final HttpServerExchange exchange) throws Exception {
+ String location = NO_REDIRECT;
+ // Both ports should likely never be less than 0, but should result in a NO_REDIRECT if they are
+ if (port > -1 || securePort > -1) {
+ try {
+ // Use secure port if available by default
+ if (securePort > -1) {
+ location = assembleURI(HTTPS, secureNetworkInterfaceBinding, securePort, SECURE_DEFAULT_PORT, exchange);
+ } else {
+ location = assembleURI(HTTP, networkInterfaceBinding, port, DEFAULT_PORT, exchange);
+ }
+ } catch (URISyntaxException e) {
+ UndertowLogger.ROOT_LOGGER.invalidRedirectURI(e);
+ }
+ }
+ // Use a new redirect each time as different clients could be requesting the console with different host names
+ final RedirectHandler redirectHandler = new RedirectHandler(location);
+ redirectHandler.handleRequest(exchange);
+ }
+
+ private String assembleURI(final String scheme, final NetworkInterfaceBinding interfaceBinding, final int port, final int defaultPort, final HttpServerExchange exchange)
+ throws URISyntaxException {
+ final int p = (port != defaultPort ? port : -1);
+ final String hostname = getRedirectHostname(interfaceBinding.getAddress(), exchange);
+ if (hostname == null) {
+ return NO_REDIRECT;
+ }
+ return new URI(scheme, null, hostname, p, CONSOLE_PATH, null, null).toString();
+ }
+
+ private String getRedirectHostname(final InetAddress managementAddress, final HttpServerExchange exchange) {
+ final InetAddress destinationAddress = exchange.getDestinationAddress().getAddress();
+ // If hosts are equal use the host from the header
+ if (managementAddress.equals(destinationAddress) || managementAddress.isAnyLocalAddress()) {
+ String hostname = exchange.getRequestHeaders().getFirst(Headers.HOST);
+ if (hostname != null) {
+ // Remove the port if it exists
+ final int portPos = hostname.indexOf(':');
+ if (portPos > 0) {
+ hostname = hostname.substring(0, portPos);
+ }
+ return hostname;
+ }
+ }
+
+ // Host names don't match, use the IP address of the management host if both are loopback
+ if (managementAddress.isLoopbackAddress() && destinationAddress.isLoopbackAddress()) {
+ String hostname = managementAddress.getHostAddress();
+ final int zonePos = hostname.indexOf('%');
+ if (zonePos > 0) {
+ // Remove the zone identifier
+ hostname = hostname.substring(0, zonePos);
+ }
+ return hostname;
+ }
+
+ // Nothing matched, don't expose the management IP
+ return null;
+ }
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/Constants.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/Constants.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/Constants.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,264 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+/**
+ * @author Tomaz Cerar (c) 2012 Red Hat Inc.
+ */
+
+public interface Constants {
+ String ACCESS_LOG = "access-log";
+ String AJP_LISTENER = "ajp-listener";
+ String BUFFER_CACHE = "buffer-cache";
+ String BUFFER_CACHES = "buffer-caches";
+ String BUFFER_SIZE = "buffer-size";
+ String BUFFERS_PER_REGION = "buffers-per-region";
+ String CONFIGURATION = "configuration";
+ String MAX_REGIONS = "max-regions";
+ String BUFFER_POOL = "buffer-pool";
+ String SETTING = "setting";
+ String SECURITY_REALM = "security-realm";
+ String SOCKET_BINDING = "socket-binding";
+ String SSL_CONTEXT = "ssl-context";
+ String PATH = "path";
+ String HTTP_LISTENER = "http-listener";
+ String HTTPS_LISTENER = "https-listener";
+ String HTTP_INVOKER = "http-invoker";
+ String LISTENER = "listener";
+ String INSTANCE_ID = "instance-id";
+ String NAME = "name";
+ String WORKER = "worker";
+ String SERVLET_CONTAINER = "servlet-container";
+ String LOCATION = "location";
+ String JSP = "jsp";
+ String JSP_CONFIG = "jsp-config";
+ String HANDLER = "handler";
+ String HANDLERS = "handlers";
+ String SERVER = "server";
+ String HOST = "host";
+ String PATTERN = "pattern";
+ String PREFIX = "prefix";
+ String SUFFIX = "suffix";
+ String ROTATE = "rotate";
+ //String CLASS = "class";
+ String DEFAULT_HOST = "default-host";
+ String DEFAULT_VIRTUAL_HOST = "default-virtual-host";
+ String DEFAULT_SERVLET_CONTAINER = "default-servlet-container";
+ String DEFAULT_SERVER = "default-server";
+ String DEFAULT_WEB_MODULE = "default-web-module";
+ String ALIAS = "alias";
+ String ERROR_PAGE = "error-page";
+ String ERROR_PAGES = "error-pages";
+ String SIMPLE_ERROR_PAGE = "simple-error-page";
+ String SCHEME = "scheme";
+ String MAX_POST_SIZE = "max-post-size";
+ String DEFAULT_RESPONSE_CODE = "default-response-code";
+ /*JSP config */
+ String CHECK_INTERVAL = "check-interval";
+ String CONTAINER = "container";
+ String DEVELOPMENT = "development";
+ String DISABLED = "disabled";
+ String DISPLAY_SOURCE_FRAGMENT = "display-source-fragment";
+ String DUMP_SMAP = "dump-smap";
+ String ERROR_ON_USE_BEAN_INVALID_CLASS_ATTRIBUTE = "error-on-use-bean-invalid-class-attribute";
+ String FILE = "file";
+ String FILE_ENCODING = "file-encoding";
+ String GENERATE_STRINGS_AS_CHAR_ARRAYS = "generate-strings-as-char-arrays";
+ String OPTIMIZE_SCRIPTLETS = "optimize-scriptlets";
+ String JAVA_ENCODING = "java-encoding";
+ String JSP_CONFIGURATION = "jsp-configuration";
+ String KEEP_GENERATED = "keep-generated";
+ String LISTINGS = "listings";
+ String MAPPED_FILE = "mapped-file";
+ String MAX_DEPTH = "max-depth";
+ String MIME_MAPPING = "mime-mapping";
+ String MODIFICATION_TEST_INTERVAL = "modification-test-interval";
+ String READ_ONLY = "read-only";
+ String RECOMPILE_ON_FAIL = "recompile-on-fail";
+ String SCRATCH_DIR = "scratch-dir";
+ String SECRET = "secret";
+ String SENDFILE = "sendfile";
+ String SINGLE_SIGN_ON = "single-sign-on";
+ String SMAP = "smap";
+ String SOURCE_VM = "source-vm";
+ String SSL = "ssl";
+ String STATIC_RESOURCES = "static-resources";
+ String TAG_POOLING = "tag-pooling";
+ String TARGET_VM = "target-vm";
+ String TRIM_SPACES = "trim-spaces";
+ String WEBDAV = "webdav";
+ String WELCOME_FILE = "welcome-file";
+ String X_POWERED_BY = "x-powered-by";
+ String ENABLED = "enabled";
+ String DIRECTORY_LISTING = "directory-listing";
+ String FILTER = "filter";
+ String FILTERS = "filters";
+ String FILTER_REF = "filter-ref";
+
+ //session cookie config
+ String SESSION_COOKIE = "session-cookie";
+ String DOMAIN = "domain";
+ String COMMENT = "comment";
+ String HTTP_ONLY = "http-only";
+ String SECURE = "secure";
+ String MAX_AGE = "max-age";
+ String ALLOW_NON_STANDARD_WRAPPERS = "allow-non-standard-wrappers";
+
+ String PERSISTENT_SESSIONS = "persistent-sessions";
+ String DEFAULT_BUFFER_CACHE = "default-buffer-cache";
+
+ String RELATIVE_TO = "relative-to";
+ String REDIRECT_SOCKET = "redirect-socket";
+ String DIRECTORY = "directory";
+ String STACK_TRACE_ON_ERROR = "stack-trace-on-error";
+ String DEFAULT_ENCODING = "default-encoding";
+ String USE_LISTENER_ENCODING = "use-listener-encoding";
+ String NONE = "none";
+ String PROBLEM_SERVER_RETRY = "problem-server-retry";
+ String STICKY_SESSION_LIFETIME = "sticky-session-lifetime";
+ String SESSION_COOKIE_NAMES = "session-cookie-names";
+ String CONNECTIONS_PER_THREAD = "connections-per-thread";
+ String REVERSE_PROXY = "reverse-proxy";
+ String MAX_REQUEST_TIME = "max-request-time";
+ String CERTIFICATE_FORWARDING = "certificate-forwarding";
+ String OPTIONS = "options";
+ String IGNORE_FLUSH = "ignore-flush";
+
+ String WEBSOCKETS = "websockets";
+ //mod_cluster
+ String MOD_CLUSTER = "mod-cluster";
+ String MANAGEMENT_SOCKET_BINDING = "management-socket-binding";
+ String ADVERTISE_SOCKET_BINDING = "advertise-socket-binding";
+ String SECURITY_KEY = "security-key";
+ String ADVERTISE_PROTOCOL = "advertise-protocol";
+ String ADVERTISE_PATH = "advertise-path";
+ String ADVERTISE_FREQUENCY = "advertise-frequency";
+ String HEALTH_CHECK_INTERVAL = "health-check-interval";
+ String BROKEN_NODE_TIMEOUT = "broken-node-timeout";
+ String MANAGEMENT_ACCESS_PREDICATE = "management-access-predicate";
+ String REQUEST_QUEUE_SIZE = "request-queue-size";
+ String CACHED_CONNECTIONS_PER_THREAD = "cached-connections-per-thread";
+ String CONNECTION_IDLE_TIMEOUT = "connection-idle-timeout";
+ String FAILOVER_STRATEGY = "failover-strategy";
+
+ String USE_SERVER_LOG = "use-server-log";
+ String VALUE = "value";
+
+ String REWRITE = "rewrite";
+ String DISALLOWED_METHODS = "disallowed-methods";
+ String RESOLVE_PEER_ADDRESS = "resolve-peer-address";
+ String BALANCER = "balancer";
+ String CONTEXT = "context";
+ String NODE = "node";
+ String STATUS = "status";
+ String REQUESTS = "requests";
+ String ENABLE = "enable";
+ String DISABLE = "disable";
+ String LOAD = "load";
+ String USE_ALIAS = "use-alias";
+ String LOAD_BALANCING_GROUP = "load-balancing-group";
+ String CACHE_CONNECTIONS = "cache-connections";
+ String FLUSH_WAIT = "flush-wait";
+ String MAX_CONNECTIONS = "max-connections";
+ String OPEN_CONNECTIONS = "open-connections";
+ String PING = "ping";
+ String READ = "read";
+ String SMAX = "smax";
+ String TIMEOUT = "timeout";
+ String WRITTEN = "written";
+ String TTL = "ttl";
+
+ String STICKY_SESSION = "sticky-session";
+ String STICKY_SESSION_COOKIE = "sticky-session-cookie";
+ String STICKY_SESSION_PATH = "sticky-session-path";
+ String STICKY_SESSION_FORCE = "sticky-session-force";
+ String STICKY_SESSION_REMOVE= "sticky-session-remove";
+ String WAIT_WORKER = "wait-worker";
+ String MAX_ATTEMPTS = "max-attempts";
+ String FLUSH_PACKETS = "flush-packets";
+ String QUEUE_NEW_REQUESTS = "queue-new-requests";
+ String STOP = "stop";
+ String ENABLE_NODES = "enable-nodes";
+ String DISABLE_NODES = "disable-nodes";
+ String STOP_NODES = "stop-nodes";
+ String DEFAULT_SESSION_TIMEOUT = "default-session-timeout";
+ String PREDICATE = "predicate";
+ String SSL_SESSION_CACHE_SIZE = "ssl-session-cache-size";
+ String SSL_SESSION_TIMEOUT = "ssl-session-timeout";
+ String VERIFY_CLIENT = "verify-client";
+ String ENABLED_CIPHER_SUITES = "enabled-cipher-suites";
+ String ENABLED_PROTOCOLS = "enabled-protocols";
+ String ENABLE_HTTP2 = "enable-http2";
+ String ENABLE_SPDY = "enable-spdy";
+ String URI = "uri";
+ String ALIASES = "aliases";
+ String ELECTED = "elected";
+ String PROACTIVE_AUTHENTICATION = "proactive-authentication";
+ String SESSION_ID_LENGTH = "session-id-length";
+ String EXTENDED = "extended";
+ String MAX_BUFFERED_REQUEST_SIZE = "max-buffered-request-size";
+ String MAX_SESSIONS = "max-sessions";
+ String USER_AGENTS = "user-agents";
+ String SESSION_TIMEOUT = "session-timeout";
+ String CRAWLER_SESSION_MANAGEMENT = "crawler-session-management";
+ String MAX_AJP_PACKET_SIZE = "max-ajp-packet-size";
+ String STATISTICS_ENABLED = "statistics-enabled";
+ String DEFAULT_SECURITY_DOMAIN = "default-security-domain";
+ String DISABLE_FILE_WATCH_SERVICE = "disable-file-watch-service";
+ String DISABLE_SESSION_ID_REUSE = "disable-session-id-reuse";
+ String PER_MESSAGE_DEFLATE = "per-message-deflate";
+ String DEFLATER_LEVEL = "deflater-level";
+ String MAX_RETRIES = "max-retries";
+
+ // Elytron Integration
+ String APPLICATION_SECURITY_DOMAIN = "application-security-domain";
+ String APPLICATION_SECURITY_DOMAINS = "application-security-domains";
+ String HTTP_AUTHENITCATION_FACTORY = "http-authentication-factory";
+ String OVERRIDE_DEPLOYMENT_CONFIG = "override-deployment-config";
+ String REFERENCING_DEPLOYMENTS = "referencing-deployments";
+ String SECURITY_DOMAIN = "security-domain";
+ String ENABLE_JACC = "enable-jacc";
+
+ String FILE_CACHE_MAX_FILE_SIZE = "file-cache-max-file-size";
+ String FILE_CACHE_METADATA_SIZE = "file-cache-metadata-size";
+ String FILE_CACHE_TIME_TO_LIVE = "file-cache-time-to-live";
+ String SESSION_ID = "session-id";
+ String ATTRIBUTE = "attribute";
+ String INVALIDATE_SESSION = "invalidate-session";
+ String LIST_SESSIONS = "list-sessions";
+ String LIST_SESSION_ATTRIBUTE_NAMES = "list-session-attribute-names";
+ String LIST_SESSION_ATTRIBUTES = "list-session-attributes";
+ String GET_SESSION_ATTRIBUTE = "get-session-attribute";
+ String GET_SESSION_LAST_ACCESSED_TIME = "get-session-last-accessed-time";
+ String GET_SESSION_LAST_ACCESSED_TIME_MILLIS = "get-session-last-accessed-time-millis";
+ String GET_SESSION_CREATION_TIME = "get-session-creation-time";
+ String GET_SESSION_CREATION_TIME_MILLIS = "get-session-creation-time-millis";
+ String DEFAULT_COOKIE_VERSION = "default-cookie-version";
+
+ String PROXY_PROTOCOL = "proxy-protocol";
+ String MAX_POOL_SIZE = "max-pool-size";
+ String THREAD_LOCAL_CACHE_SIZE = "thread-local-cache-size";
+ String DIRECT = "direct";
+ String LEAK_DETECTION_PERCENT = "leak-detection-percent";
+ String BYTE_BUFFER_POOL = "byte-buffer-pool";
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/CrawlerSessionManagementDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/CrawlerSessionManagementDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/CrawlerSessionManagementDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,146 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import io.undertow.servlet.api.CrawlerSessionManagerConfig;
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.as.controller.PersistentResourceDefinition;
+import org.jboss.as.controller.RestartParentResourceAddHandler;
+import org.jboss.as.controller.RestartParentResourceRemoveHandler;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.client.helpers.MeasurementUnit;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+import org.jboss.msc.service.ServiceName;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * Global session cookie config
+ *
+ * @author Stuart Douglas
+ */
+class CrawlerSessionManagementDefinition extends PersistentResourceDefinition {
+
+ static final CrawlerSessionManagementDefinition INSTANCE = new CrawlerSessionManagementDefinition();
+
+ protected static final SimpleAttributeDefinition USER_AGENTS =
+ new SimpleAttributeDefinitionBuilder(Constants.USER_AGENTS, ModelType.STRING, true)
+ .setRestartAllServices()
+ .setAllowExpression(true)
+ .build();
+ protected static final SimpleAttributeDefinition SESSION_TIMEOUT =
+ new SimpleAttributeDefinitionBuilder(Constants.SESSION_TIMEOUT, ModelType.INT, true)
+ .setRestartAllServices()
+ .setMeasurementUnit(MeasurementUnit.SECONDS)
+ .setAllowExpression(true)
+ .build();
+
+ protected static final SimpleAttributeDefinition[] ATTRIBUTES = {
+ USER_AGENTS,
+ SESSION_TIMEOUT
+ };
+ static final Map ATTRIBUTES_MAP = new HashMap<>();
+
+ static {
+ for (SimpleAttributeDefinition attr : ATTRIBUTES) {
+ ATTRIBUTES_MAP.put(attr.getName(), attr);
+ }
+ }
+
+
+ private CrawlerSessionManagementDefinition() {
+ super(UndertowExtension.CRAWLER_SESSION_MANAGEMENT,
+ UndertowExtension.getResolver(UndertowExtension.CRAWLER_SESSION_MANAGEMENT.getKeyValuePair()),
+ new CrawlerSessionManagementAdd(),
+ new CrawlerSessionManagementRemove());
+ }
+
+ @Override
+ public Collection getAttributes() {
+ return ATTRIBUTES_MAP.values();
+ }
+
+ public CrawlerSessionManagerConfig getConfig(final OperationContext context, final ModelNode model) throws OperationFailedException {
+ if(!model.isDefined()) {
+ return null;
+ }
+ ModelNode agents = USER_AGENTS.resolveModelAttribute(context, model);
+ ModelNode timeout = SESSION_TIMEOUT.resolveModelAttribute(context, model);
+ if(timeout.isDefined() && agents.isDefined()) {
+ return new CrawlerSessionManagerConfig(timeout.asInt(), agents.asString());
+ } else if(timeout.isDefined()) {
+ return new CrawlerSessionManagerConfig(timeout.asInt());
+ } else if(agents.isDefined()) {
+ return new CrawlerSessionManagerConfig(agents.asString());
+ }
+ return new CrawlerSessionManagerConfig();
+ }
+
+
+ private static class CrawlerSessionManagementAdd extends RestartParentResourceAddHandler {
+ protected CrawlerSessionManagementAdd() {
+ super(ServletContainerDefinition.INSTANCE.getPathElement().getKey());
+ }
+
+ @Override
+ protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException {
+ for (AttributeDefinition def : ATTRIBUTES) {
+ def.validateAndSet(operation, model);
+ }
+ }
+
+ @Override
+ protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException {
+ ServletContainerAdd.INSTANCE.installRuntimeServices(context, parentModel, parentAddress.getLastElement().getValue());
+ }
+
+ @Override
+ protected ServiceName getParentServiceName(PathAddress parentAddress) {
+ return UndertowService.SERVLET_CONTAINER.append(parentAddress.getLastElement().getValue());
+ }
+ }
+
+ private static class CrawlerSessionManagementRemove extends RestartParentResourceRemoveHandler {
+
+ protected CrawlerSessionManagementRemove() {
+ super(ServletContainerDefinition.INSTANCE.getPathElement().getKey());
+ }
+
+ @Override
+ protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException {
+ ServletContainerAdd.INSTANCE.installRuntimeServices(context, parentModel, parentAddress.getLastElement().getValue());
+ }
+
+ @Override
+ protected ServiceName getParentServiceName(PathAddress parentAddress) {
+ return UndertowService.SERVLET_CONTAINER.append(parentAddress.getLastElement().getValue());
+ }
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/DefaultResponseCodeHandler.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/DefaultResponseCodeHandler.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/DefaultResponseCodeHandler.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,67 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import io.undertow.server.HttpHandler;
+import io.undertow.server.HttpServerExchange;
+import io.undertow.util.StatusCodes;
+
+import org.jboss.logging.Logger;
+
+/**
+ * Simple hander to set default code
+ *
+ * @author baranowb
+ *
+ */
+public class DefaultResponseCodeHandler implements HttpHandler {
+
+ protected static final Logger log = Logger.getLogger(DefaultResponseCodeHandler.class);
+ protected static final boolean traceEnabled;
+ static {
+ traceEnabled = log.isTraceEnabled();
+ }
+
+ private final int responseCode;
+ private volatile boolean suspended = false;
+
+ public DefaultResponseCodeHandler(final int defaultCode) {
+ this.responseCode = defaultCode;
+ }
+
+ @Override
+ public void handleRequest(HttpServerExchange exchange) throws Exception {
+ if(suspended) {
+ exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE);
+ } else {
+ exchange.setStatusCode(this.responseCode);
+ }
+ if (traceEnabled) {
+ log.tracef("Setting response code %s for exchange %s", responseCode, exchange);
+ }
+ }
+
+ public void setSuspended(boolean suspended) {
+ this.suspended = suspended;
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,440 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP;
+import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM;
+
+import java.time.Instant;
+import java.time.ZoneId;
+import java.time.format.DateTimeFormatter;
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+import org.jboss.as.controller.AbstractRuntimeOnlyHandler;
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationDefinition;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.as.controller.PathElement;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.SimpleOperationDefinitionBuilder;
+import org.jboss.as.controller.SimpleResourceDefinition;
+import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
+import org.jboss.as.controller.descriptions.ResourceDescriptionResolver;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+import org.jboss.as.controller.registry.Resource;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+import org.jboss.dmr.Property;
+import org.jboss.msc.service.ServiceController;
+import org.wildfly.extension.undertow.deployment.UndertowDeploymentService;
+import org.wildfly.extension.undertow.logging.UndertowLogger;
+
+import io.undertow.server.session.Session;
+import io.undertow.server.session.SessionManager;
+import io.undertow.server.session.SessionManagerStatistics;
+import io.undertow.servlet.api.Deployment;
+
+/**
+ * @author Tomaz Cerar
+ */
+public class DeploymentDefinition extends SimpleResourceDefinition {
+
+ private static final ResourceDescriptionResolver DEFAULT_RESOLVER = UndertowExtension.getResolver("deployment");
+
+ public static final DeploymentDefinition INSTANCE = new DeploymentDefinition();
+
+ public static final AttributeDefinition SERVER = new SimpleAttributeDefinitionBuilder("server", ModelType.STRING).setStorageRuntime().build();
+ public static final AttributeDefinition CONTEXT_ROOT = new SimpleAttributeDefinitionBuilder("context-root", ModelType.STRING).setStorageRuntime().build();
+ public static final AttributeDefinition VIRTUAL_HOST = new SimpleAttributeDefinitionBuilder("virtual-host", ModelType.STRING).setStorageRuntime().build();
+ static final AttributeDefinition SESSIOND_ID = new SimpleAttributeDefinitionBuilder(Constants.SESSION_ID, ModelType.STRING)
+ .setRequired(true)
+ .setAllowExpression(false)
+ .build();
+
+ static final AttributeDefinition ATTRIBUTE = new SimpleAttributeDefinitionBuilder(Constants.ATTRIBUTE, ModelType.STRING)
+ .setRequired(true)
+ .setAllowExpression(false)
+ .build();
+
+
+ static final OperationDefinition INVALIDATE_SESSION = new SimpleOperationDefinitionBuilder(Constants.INVALIDATE_SESSION, DEFAULT_RESOLVER)
+ .addParameter(SESSIOND_ID)
+ .setRuntimeOnly()
+ .setReplyType(ModelType.BOOLEAN)
+ .build();
+
+ static final OperationDefinition LIST_SESSIONS = new SimpleOperationDefinitionBuilder(Constants.LIST_SESSIONS, DEFAULT_RESOLVER)
+ .setRuntimeOnly()
+ .setReplyType(ModelType.LIST)
+ .setReplyValueType(ModelType.STRING)
+ .build();
+
+ static final OperationDefinition LIST_SESSION_ATTRIBUTE_NAMES = new SimpleOperationDefinitionBuilder(Constants.LIST_SESSION_ATTRIBUTE_NAMES, DEFAULT_RESOLVER)
+ .setRuntimeOnly()
+ .addParameter(SESSIOND_ID)
+ .setReplyType(ModelType.LIST)
+ .setReplyValueType(ModelType.STRING)
+ .build();
+
+ static final OperationDefinition LIST_SESSION_ATTRIBUTES = new SimpleOperationDefinitionBuilder(Constants.LIST_SESSION_ATTRIBUTES, DEFAULT_RESOLVER)
+ .setRuntimeOnly()
+ .addParameter(SESSIOND_ID)
+ .setReplyType(ModelType.LIST)
+ .setReplyValueType(ModelType.PROPERTY)
+ .build();
+
+ static final OperationDefinition GET_SESSION_ATTRIBUTE = new SimpleOperationDefinitionBuilder(Constants.GET_SESSION_ATTRIBUTE, DEFAULT_RESOLVER)
+ .setRuntimeOnly()
+ .addParameter(SESSIOND_ID)
+ .addParameter(ATTRIBUTE)
+ .setReplyType(ModelType.STRING)
+ .setReplyValueType(ModelType.PROPERTY)
+ .build();
+
+ static final OperationDefinition GET_SESSION_LAST_ACCESSED_TIME = new SimpleOperationDefinitionBuilder(Constants.GET_SESSION_LAST_ACCESSED_TIME, DEFAULT_RESOLVER)
+ .setRuntimeOnly()
+ .addParameter(SESSIOND_ID)
+ .setReplyType(ModelType.STRING)
+ .build();
+
+
+ static final OperationDefinition GET_SESSION_LAST_ACCESSED_TIME_MILLIS = new SimpleOperationDefinitionBuilder(Constants.GET_SESSION_LAST_ACCESSED_TIME_MILLIS, DEFAULT_RESOLVER)
+ .setRuntimeOnly()
+ .addParameter(SESSIOND_ID)
+ .setReplyType(ModelType.LONG)
+ .build();
+
+ static final OperationDefinition GET_SESSION_CREATION_TIME = new SimpleOperationDefinitionBuilder(Constants.GET_SESSION_CREATION_TIME, DEFAULT_RESOLVER)
+ .setRuntimeOnly()
+ .addParameter(SESSIOND_ID)
+ .setReplyType(ModelType.STRING)
+ .build();
+
+
+ static final OperationDefinition GET_SESSION_CREATION_TIME_MILLIS = new SimpleOperationDefinitionBuilder(Constants.GET_SESSION_CREATION_TIME_MILLIS, DEFAULT_RESOLVER)
+ .setRuntimeOnly()
+ .addParameter(SESSIOND_ID)
+ .setReplyType(ModelType.LONG)
+ .build();
+
+ private DeploymentDefinition() {
+ super(new Parameters(PathElement.pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), DEFAULT_RESOLVER)
+ .setFeature(false));
+ }
+
+
+ @Override
+ public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
+ resourceRegistration.registerReadOnlyAttribute(CONTEXT_ROOT, null);
+ resourceRegistration.registerReadOnlyAttribute(VIRTUAL_HOST, null);
+ resourceRegistration.registerReadOnlyAttribute(SERVER, null);
+ for (SessionStat stat : SessionStat.values()) {
+ resourceRegistration.registerMetric(stat.definition, SessionManagerStatsHandler.getInstance());
+ }
+ }
+
+ @Override
+ public void registerOperations(ManagementResourceRegistration resourceRegistration) {
+ super.registerOperations(resourceRegistration);
+ SessionManagerOperationHandler handler = new SessionManagerOperationHandler();
+
+ resourceRegistration.registerOperationHandler(INVALIDATE_SESSION, handler);
+ resourceRegistration.registerOperationHandler(LIST_SESSIONS, handler);
+ resourceRegistration.registerOperationHandler(LIST_SESSION_ATTRIBUTE_NAMES, handler);
+ resourceRegistration.registerOperationHandler(LIST_SESSION_ATTRIBUTES, handler);
+ resourceRegistration.registerOperationHandler(GET_SESSION_ATTRIBUTE, handler);
+ resourceRegistration.registerOperationHandler(GET_SESSION_LAST_ACCESSED_TIME, handler);
+ resourceRegistration.registerOperationHandler(GET_SESSION_LAST_ACCESSED_TIME_MILLIS, handler);
+ resourceRegistration.registerOperationHandler(GET_SESSION_CREATION_TIME, handler);
+ resourceRegistration.registerOperationHandler(GET_SESSION_CREATION_TIME_MILLIS, handler);
+ }
+
+ static class SessionManagerOperationHandler extends AbstractRuntimeOnlyHandler {
+
+ @Override
+ protected void executeRuntimeStep(OperationContext operationContext, ModelNode modelNode) throws OperationFailedException {
+ ModelNode result = new ModelNode();
+ SessionManager sessionManager = getSessionManager(operationContext, modelNode);
+
+ String name = modelNode.get(OP).asString();
+ //list-sessions does not take a session id param
+ if (name.equals(Constants.LIST_SESSIONS)) {
+ result.setEmptyList();
+ Set sessions = sessionManager.getAllSessions();
+ for (String s : sessions) {
+ result.add(s);
+ }
+ operationContext.getResult().set(result);
+ return;
+ }
+ String sessionId = SESSIOND_ID.resolveModelAttribute(operationContext, modelNode).asString();
+ Session session = sessionManager.getSession(sessionId);
+ if (session == null && !name.equals(Constants.INVALIDATE_SESSION)) {
+ throw UndertowLogger.ROOT_LOGGER.sessionNotFound(sessionId);
+ }
+
+ switch (name) {
+ case Constants.INVALIDATE_SESSION: {
+ if(session == null) {
+ result.set(false);
+ } else {
+ session.invalidate(null);
+ result.set(true);
+ }
+ break;
+ }
+ case Constants.LIST_SESSION_ATTRIBUTE_NAMES: {
+ result.setEmptyList();
+ Set sessions = session.getAttributeNames();
+ for (String s : sessions) {
+ result.add(s);
+ }
+ break;
+ }
+ case Constants.LIST_SESSION_ATTRIBUTES: {
+ result.setEmptyList();
+ Set sessions = session.getAttributeNames();
+ for (String s : sessions) {
+ Object attribute = session.getAttribute(s);
+ ModelNode m = new ModelNode();
+ if (attribute != null) {
+ m.set(attribute.toString());
+ }
+ result.add(new Property(s, m));
+ }
+ break;
+ }
+ case Constants.GET_SESSION_ATTRIBUTE: {
+ String a = ATTRIBUTE.resolveModelAttribute(operationContext, modelNode).asString();
+ Object attribute = session.getAttribute(a);
+ if (attribute != null) {
+ result.set(attribute.toString());
+ }
+ break;
+ }
+ case Constants.GET_SESSION_LAST_ACCESSED_TIME: {
+ long accessTime = session.getLastAccessedTime();
+ result.set(DateTimeFormatter.ISO_DATE_TIME
+ .withZone(ZoneId.systemDefault())
+ .format(Instant.ofEpochMilli(accessTime)));
+ break;
+ }
+ case Constants.GET_SESSION_LAST_ACCESSED_TIME_MILLIS: {
+ long accessTime = session.getLastAccessedTime();
+ result.set(accessTime);
+ break;
+ }
+ case Constants.GET_SESSION_CREATION_TIME: {
+ long accessTime = session.getCreationTime();
+ result.set(DateTimeFormatter.ISO_DATE_TIME
+ .withZone(ZoneId.systemDefault())
+ .format(Instant.ofEpochMilli(accessTime)));
+ break;
+ }
+ case Constants.GET_SESSION_CREATION_TIME_MILLIS: {
+ long accessTime = session.getCreationTime();
+ result.set(accessTime);
+ break;
+ }
+ }
+
+ operationContext.getResult().set(result);
+ }
+ }
+
+ static class SessionManagerStatsHandler extends AbstractRuntimeOnlyHandler {
+
+ static SessionManagerStatsHandler INSTANCE = new SessionManagerStatsHandler();
+
+ private SessionManagerStatsHandler() {
+ }
+
+ public static SessionManagerStatsHandler getInstance() {
+ return INSTANCE;
+ }
+
+ @Override
+ protected void executeRuntimeStep(OperationContext context, ModelNode operation) throws OperationFailedException {
+
+ final PathAddress address = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR));
+
+ final Resource web = context.readResourceFromRoot(address.subAddress(0, address.size()), false);
+ final ModelNode subModel = web.getModel();
+
+ final String host = VIRTUAL_HOST.resolveModelAttribute(context, subModel).asString();
+ final String path = CONTEXT_ROOT.resolveModelAttribute(context, subModel).asString();
+ final String server = SERVER.resolveModelAttribute(context, subModel).asString();
+
+ SessionStat stat = SessionStat.getStat(operation.require(ModelDescriptionConstants.NAME).asString());
+
+ if (stat == null) {
+ context.getFailureDescription().set(UndertowLogger.ROOT_LOGGER.unknownMetric(operation.require(ModelDescriptionConstants.NAME).asString()));
+ } else {
+ ModelNode result = new ModelNode();
+ final ServiceController> controller = context.getServiceRegistry(false).getService(UndertowService.deploymentServiceName(server, host, path));
+ if (controller != null && controller.getState() != ServiceController.State.UP) {//check if deployment is active at all
+ return;
+ }
+ final UndertowDeploymentService deploymentService = (UndertowDeploymentService) controller.getService();
+ if (deploymentService == null || deploymentService.getDeployment() == null) { //we might be in shutdown and it is possible
+ return;
+ }
+ Deployment deployment = deploymentService.getDeployment();
+ SessionManager sessionManager = deployment.getSessionManager();
+ SessionManagerStatistics sms = sessionManager.getStatistics();
+
+ switch (stat) {
+ case ACTIVE_SESSIONS:
+ result.set(sessionManager.getActiveSessions().size());
+ break;
+ case EXPIRED_SESSIONS:
+ if (sms == null) {
+ result.set(0);
+ } else {
+ result.set((int) sms.getExpiredSessionCount());
+ }
+ break;
+ case MAX_ACTIVE_SESSIONS:
+ if (sms == null) {
+ result.set(0);
+ } else {
+ result.set((int) sms.getMaxActiveSessions());
+ }
+ break;
+ case SESSIONS_CREATED:
+ if (sms == null) {
+ result.set(0);
+ } else {
+ result.set((int) sms.getCreatedSessionCount());
+ }
+ break;
+ //case DUPLICATED_SESSION_IDS:
+ // result.set(sm.getDuplicates());
+ // break;
+ case SESSION_AVG_ALIVE_TIME:
+ if (sms == null) {
+ result.set(0);
+ } else {
+ result.set((int) sms.getAverageSessionAliveTime() / 1000);
+ }
+ break;
+ case SESSION_MAX_ALIVE_TIME:
+ if (sms == null) {
+ result.set(0);
+ } else {
+ result.set((int) sms.getMaxSessionAliveTime() / 1000);
+ }
+ break;
+ case REJECTED_SESSIONS:
+ if (sms == null) {
+ result.set(0);
+ } else {
+ result.set((int) sms.getRejectedSessions());
+ }
+ break;
+ case HIGHEST_SESSION_COUNT:
+ if (sms == null) {
+ result.set(0);
+ } else {
+ result.set((int) sms.getHighestSessionCount());
+ }
+ break;
+ default:
+ throw new IllegalStateException(UndertowLogger.ROOT_LOGGER.unknownMetric(stat));
+ }
+ context.getResult().set(result);
+ }
+ }
+ }
+
+ private static SessionManager getSessionManager(OperationContext context, ModelNode operation) throws OperationFailedException {
+ final PathAddress address = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR));
+ final Resource web = context.readResourceFromRoot(address.subAddress(0, address.size()), false);
+ final ModelNode subModel = web.getModel();
+ final String host = VIRTUAL_HOST.resolveModelAttribute(context, subModel).asString();
+ final String path = CONTEXT_ROOT.resolveModelAttribute(context, subModel).asString();
+ final String server = SERVER.resolveModelAttribute(context, subModel).asString();
+
+ final UndertowDeploymentService deploymentService;
+ final ServiceController> controller = context.getServiceRegistry(false).getService(UndertowService.deploymentServiceName(server, host, path));
+ if (controller != null && controller.getState() != ServiceController.State.UP) {//check if deployment is active at all
+ throw UndertowLogger.ROOT_LOGGER.sessionManagerNotAvailable();
+ } else {
+ deploymentService = (UndertowDeploymentService) controller.getService();
+ if (deploymentService == null || deploymentService.getDeployment() == null) { //we might be in shutdown and it is possible
+ throw UndertowLogger.ROOT_LOGGER.sessionManagerNotAvailable();
+ }
+ }
+ Deployment deployment = deploymentService.getDeployment();
+ return deployment.getSessionManager();
+ }
+
+ public enum SessionStat {
+ ACTIVE_SESSIONS(new SimpleAttributeDefinitionBuilder("active-sessions", ModelType.INT)
+ .setUndefinedMetricValue(new ModelNode(0)).setStorageRuntime().build()),
+ EXPIRED_SESSIONS(new SimpleAttributeDefinitionBuilder("expired-sessions", ModelType.INT)
+ .setUndefinedMetricValue(new ModelNode(0)).setStorageRuntime().build()),
+ SESSIONS_CREATED(new SimpleAttributeDefinitionBuilder("sessions-created", ModelType.INT)
+ .setUndefinedMetricValue(new ModelNode(0)).setStorageRuntime().build()),
+ //DUPLICATED_SESSION_IDS(new SimpleAttributeDefinition("duplicated-session-ids", ModelType.INT, false)),
+ SESSION_AVG_ALIVE_TIME(new SimpleAttributeDefinitionBuilder("session-avg-alive-time", ModelType.INT)
+ .setUndefinedMetricValue(new ModelNode(0)).setStorageRuntime().build()),
+ SESSION_MAX_ALIVE_TIME(new SimpleAttributeDefinitionBuilder("session-max-alive-time", ModelType.INT)
+ .setUndefinedMetricValue(new ModelNode(0)).setStorageRuntime().build()),
+ REJECTED_SESSIONS(new SimpleAttributeDefinitionBuilder("rejected-sessions", ModelType.INT)
+ .setUndefinedMetricValue(new ModelNode(0)).setStorageRuntime().build()),
+ MAX_ACTIVE_SESSIONS(new SimpleAttributeDefinitionBuilder("max-active-sessions", ModelType.INT)
+ .setUndefinedMetricValue(new ModelNode(0)).setStorageRuntime().build()),
+ HIGHEST_SESSION_COUNT(new SimpleAttributeDefinitionBuilder("highest-session-count", ModelType.INT)
+ .setUndefinedMetricValue(new ModelNode(0)).setStorageRuntime().build());
+
+ private static final Map MAP = new HashMap<>();
+
+ static {
+ for (SessionStat stat : EnumSet.allOf(SessionStat.class)) {
+ MAP.put(stat.toString(), stat);
+ }
+ }
+
+ final AttributeDefinition definition;
+
+ SessionStat(final AttributeDefinition definition) {
+ this.definition = definition;
+ }
+
+ @Override
+ public final String toString() {
+ return definition.getName();
+ }
+
+ public static synchronized SessionStat getStat(final String stringForm) {
+ return MAP.get(stringForm);
+ }
+ }
+
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentServletDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentServletDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentServletDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,159 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.OperationStepHandler;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.as.controller.PathElement;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.SimpleListAttributeDefinition;
+import org.jboss.as.controller.SimpleResourceDefinition;
+import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+import org.jboss.as.controller.registry.Resource;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+import org.jboss.msc.service.ServiceController;
+import org.wildfly.extension.undertow.deployment.UndertowDeploymentService;
+import org.wildfly.extension.undertow.deployment.UndertowMetricsCollector;
+
+import io.undertow.server.handlers.MetricsHandler;
+import io.undertow.servlet.api.DeploymentInfo;
+import io.undertow.servlet.api.ServletInfo;
+
+/**
+ * @author Tomaz Cerar
+ * @created 23.2.12 18:35
+ */
+public class DeploymentServletDefinition extends SimpleResourceDefinition {
+ public static final DeploymentServletDefinition INSTANCE = new DeploymentServletDefinition();
+
+ static final SimpleAttributeDefinition SERVLET_NAME = new SimpleAttributeDefinitionBuilder("servlet-name", ModelType.STRING, false).setStorageRuntime().build();
+ static final SimpleAttributeDefinition SERVLET_CLASS = new SimpleAttributeDefinitionBuilder("servlet-class", ModelType.STRING, false).setStorageRuntime().build();
+ static final SimpleAttributeDefinition MAX_REQUEST_TIME = new SimpleAttributeDefinitionBuilder("max-request-time", ModelType.LONG, true).setStorageRuntime().build();
+ static final SimpleAttributeDefinition MIN_REQUEST_TIME = new SimpleAttributeDefinitionBuilder("min-request-time", ModelType.LONG, true).setStorageRuntime().build();
+ static final SimpleAttributeDefinition TOTAL_REQUEST_TIME = new SimpleAttributeDefinitionBuilder("total-request-time", ModelType.LONG, true).setStorageRuntime().build();
+ static final SimpleAttributeDefinition REQUEST_COUNT = new SimpleAttributeDefinitionBuilder("request-count", ModelType.LONG, true).setStorageRuntime().build();
+ static final SimpleListAttributeDefinition SERVLET_MAPPINGS = new SimpleListAttributeDefinition.Builder("mappings", new SimpleAttributeDefinitionBuilder("mapping", ModelType.STRING).setRequired(false).build())
+ .setRequired(false)
+ .setStorageRuntime()
+ .build();
+
+
+ private DeploymentServletDefinition() {
+ super(PathElement.pathElement("servlet"),
+ UndertowExtension.getResolver("deployment.servlet"));
+ }
+
+ @Override
+ public void registerAttributes(ManagementResourceRegistration registration) {
+ registration.registerReadOnlyAttribute(SERVLET_NAME, null);
+ registration.registerReadOnlyAttribute(SERVLET_CLASS, null);
+ registration.registerMetric(MAX_REQUEST_TIME, new AbstractMetricsHandler() {
+ @Override
+ void handle(final ModelNode response, final String name, final MetricsHandler.MetricResult metricResult, final ServletInfo servlet) {
+ response.set((long) metricResult.getMaxRequestTime());
+ }
+ });
+ registration.registerMetric(MIN_REQUEST_TIME, new AbstractMetricsHandler() {
+ @Override
+ void handle(final ModelNode response, final String name, final MetricsHandler.MetricResult metricResult, final ServletInfo servlet) {
+ response.set((long) metricResult.getMinRequestTime());
+ }
+ });
+ registration.registerMetric(TOTAL_REQUEST_TIME, new AbstractMetricsHandler() {
+ @Override
+ void handle(final ModelNode response, final String name, final MetricsHandler.MetricResult metricResult, final ServletInfo servlet) {
+ response.set(metricResult.getTotalRequestTime());
+ }
+ });
+ registration.registerMetric(REQUEST_COUNT, new AbstractMetricsHandler() {
+ @Override
+ void handle(final ModelNode response, final String name, final MetricsHandler.MetricResult metricResult, final ServletInfo servlet) {
+ response.set(metricResult.getTotalRequests());
+ }
+ });
+ registration.registerMetric(SERVLET_MAPPINGS, new AbstractMetricsHandler() {
+ @Override
+ void handle(final ModelNode response, final String name, final MetricsHandler.MetricResult metricResult, final ServletInfo servlet) {
+ for (String mapping : servlet.getMappings()) {
+ response.add(mapping);
+ }
+ }
+
+ @Override
+ void putDefault(ModelNode response) {
+ response.setEmptyList();
+ }
+ });
+ }
+
+ abstract static class AbstractMetricsHandler implements OperationStepHandler {
+
+ abstract void handle(ModelNode response, String name, MetricsHandler.MetricResult metricResult, ServletInfo infos);
+
+ void putDefault(ModelNode response) {
+ response.set(0L);
+ }
+
+ @Override
+ public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
+ final PathAddress address = PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR));
+
+ final Resource web = context.readResourceFromRoot(address.subAddress(0, address.size() - 1), false);
+ final ModelNode subModel = web.getModel();
+
+ final String host = DeploymentDefinition.VIRTUAL_HOST.resolveModelAttribute(context, subModel).asString();
+ final String path = DeploymentDefinition.CONTEXT_ROOT.resolveModelAttribute(context, subModel).asString();
+ final String server = DeploymentDefinition.SERVER.resolveModelAttribute(context, subModel).asString();
+
+ context.addStep(new OperationStepHandler() {
+ @Override
+ public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException {
+ final ServiceController> deploymentServiceController = context.getServiceRegistry(false).getService(UndertowService.deploymentServiceName(server, host, path));
+ if (deploymentServiceController == null) {
+ return;
+ }
+ final UndertowDeploymentService deploymentService = (UndertowDeploymentService) deploymentServiceController.getService();
+ final DeploymentInfo deploymentInfo = deploymentService.getDeploymentInfoInjectedValue().getValue();
+ final UndertowMetricsCollector collector = (UndertowMetricsCollector)deploymentInfo.getMetricsCollector();
+
+ final String name = address.getLastElement().getValue();
+ final ServletInfo servlet = deploymentInfo.getServlets().get(name);
+ final ModelNode response = new ModelNode();
+ MetricsHandler.MetricResult result = collector != null ? collector.getMetrics(name) : null;
+ if (result == null) {
+ putDefault(response);
+ } else {
+ handle(response, name, result, servlet);
+ }
+ context.getResult().set(response);
+ }
+ }, OperationContext.Stage.RUNTIME);
+ }
+ }
+
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentWebSocketDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentWebSocketDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/DeploymentWebSocketDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,54 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import org.jboss.as.controller.PathElement;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.SimpleResourceDefinition;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+import org.jboss.dmr.ModelType;
+
+/**
+ * @author Stuart Douglas
+ */
+public class DeploymentWebSocketDefinition extends SimpleResourceDefinition {
+ public static final DeploymentWebSocketDefinition INSTANCE = new DeploymentWebSocketDefinition();
+
+ static final SimpleAttributeDefinition PATH = new SimpleAttributeDefinitionBuilder("path", ModelType.STRING, false).setStorageRuntime().build();
+ static final SimpleAttributeDefinition ENDPOINT_CLASS = new SimpleAttributeDefinitionBuilder("endpoint-class", ModelType.STRING, false).setStorageRuntime().build();
+
+
+
+ private DeploymentWebSocketDefinition() {
+ super(PathElement.pathElement("websocket"),
+ UndertowExtension.getResolver("deployment.websocket"));
+ }
+
+ @Override
+ public void registerAttributes(ManagementResourceRegistration registration) {
+ registration.registerReadOnlyAttribute(PATH, null);
+ registration.registerReadOnlyAttribute(ENDPOINT_CLASS, null);
+
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/DiskBasedModularPersistentSessionManager.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/DiskBasedModularPersistentSessionManager.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/DiskBasedModularPersistentSessionManager.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,134 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.wildfly.extension.undertow;
+
+import org.jboss.as.controller.services.path.PathManager;
+import org.jboss.marshalling.InputStreamByteInput;
+import org.jboss.marshalling.Marshaller;
+import org.jboss.marshalling.OutputStreamByteOutput;
+import org.jboss.marshalling.Unmarshaller;
+import org.jboss.msc.service.StartContext;
+import org.jboss.msc.service.StartException;
+import org.jboss.msc.service.StopContext;
+import org.jboss.msc.value.InjectedValue;
+import org.wildfly.extension.undertow.logging.UndertowLogger;
+import org.xnio.IoUtils;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Map;
+
+/**
+ * Persistent session manager that stores persistent session information to disk
+ *
+ * @author Stuart Douglas
+ */
+public class DiskBasedModularPersistentSessionManager extends AbstractPersistentSessionManager {
+ private final String path;
+ private final String pathRelativeTo;
+ private File baseDir;
+ private PathManager.Callback.Handle callbackHandle;
+
+ private final InjectedValue pathManager = new InjectedValue();
+
+ public DiskBasedModularPersistentSessionManager(String path, String pathRelativeTo) {
+ this.path = path;
+ this.pathRelativeTo = pathRelativeTo;
+ }
+
+ @Override
+ public synchronized void stop(StopContext stopContext) {
+ super.stop(stopContext);
+ if (callbackHandle != null) {
+ callbackHandle.remove();
+ }
+ }
+
+ @Override
+ public synchronized void start(StartContext startContext) throws StartException {
+ super.start(startContext);
+ if (pathRelativeTo != null) {
+ callbackHandle = pathManager.getValue().registerCallback(pathRelativeTo, PathManager.ReloadServerCallback.create(), PathManager.Event.UPDATED, PathManager.Event.REMOVED);
+ }
+ baseDir = new File(pathManager.getValue().resolveRelativePathEntry(path, pathRelativeTo));
+ if (!baseDir.exists()) {
+ if (!baseDir.mkdirs()) {
+ throw UndertowLogger.ROOT_LOGGER.failedToCreatePersistentSessionDir(baseDir);
+ }
+ }
+ if (!baseDir.isDirectory()) {
+ throw UndertowLogger.ROOT_LOGGER.invalidPersistentSessionDir(baseDir);
+ }
+ }
+
+
+ @Override
+ protected void persistSerializedSessions(String deploymentName, Map serializedData) throws IOException {
+ File file = new File(baseDir, deploymentName);
+ FileOutputStream out = new FileOutputStream(file, false);
+ try {
+ Marshaller marshaller = createMarshaller();
+ try {
+ marshaller.start(new OutputStreamByteOutput(out));
+ marshaller.writeObject(serializedData);
+ marshaller.finish();
+ } finally {
+ marshaller.close();
+ }
+ } finally {
+ IoUtils.safeClose(out);
+ }
+ }
+
+ @Override
+ protected Map loadSerializedSessions(String deploymentName) throws IOException {
+ File file = new File(baseDir, deploymentName);
+ if (!file.exists()) {
+ return null;
+ }
+ FileInputStream in = new FileInputStream(file);
+ try {
+ Unmarshaller unMarshaller = createUnmarshaller();
+ try {
+ try {
+ unMarshaller.start(new InputStreamByteInput(in));
+ return (Map) unMarshaller.readObject();
+ } catch (ClassNotFoundException e) {
+ throw new RuntimeException(e);
+ } finally {
+ unMarshaller.finish();
+ }
+ } finally {
+ unMarshaller.close();
+ }
+ } finally {
+ IoUtils.safeClose(in);
+ }
+
+ }
+
+ public InjectedValue getPathManager() {
+ return pathManager;
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/EventInvoker.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/EventInvoker.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/EventInvoker.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,34 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+/**
+ * Implementation of this class knows how to invoke an event on the {@link UndertowEventListener}.
+ *
+ * @author Radoslav Husar
+ * @since 8.0
+ */
+public interface EventInvoker {
+
+ void invoke(UndertowEventListener listener);
+}
\ No newline at end of file
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/FilterLocation.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/FilterLocation.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/FilterLocation.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,34 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+/**
+ * @author Stuart Douglas
+ */
+public interface FilterLocation {
+
+ void addFilter(UndertowFilter filterRef);
+
+ void removeFilter(UndertowFilter filterRef);
+
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/Handler.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/Handler.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/Handler.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,42 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.util.Collection;
+
+import io.undertow.predicate.Predicate;
+import io.undertow.server.HttpHandler;
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.dmr.ModelNode;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+public interface Handler {
+ Collection getAttributes();
+
+ Class extends HttpHandler> getHandlerClass();
+
+ HttpHandler createHttpHandler(final Predicate predicate, final ModelNode model, final HttpHandler next);
+
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/Host.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/Host.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/Host.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,417 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.CopyOnWriteArraySet;
+
+import io.undertow.Handlers;
+import io.undertow.security.api.AuthenticationMechanism;
+import io.undertow.server.HttpHandler;
+import io.undertow.server.HttpServerExchange;
+import io.undertow.server.handlers.PathHandler;
+import io.undertow.server.handlers.resource.PathResourceManager;
+import io.undertow.server.handlers.resource.ResourceHandler;
+import io.undertow.server.handlers.resource.ResourceManager;
+import io.undertow.servlet.api.Deployment;
+import io.undertow.servlet.api.DeploymentInfo;
+import io.undertow.util.CopyOnWriteMap;
+import io.undertow.util.Methods;
+import org.jboss.as.controller.ControlledProcessState;
+import org.jboss.as.controller.ControlledProcessStateService;
+import org.jboss.as.server.suspend.ServerActivity;
+import org.jboss.as.server.suspend.ServerActivityCallback;
+import org.jboss.as.server.suspend.SuspendController;
+import org.jboss.msc.service.Service;
+import org.jboss.msc.service.StartContext;
+import org.jboss.msc.service.StartException;
+import org.jboss.msc.service.StopContext;
+import org.jboss.msc.value.InjectedValue;
+import org.wildfly.extension.undertow.deployment.GateHandlerWrapper;
+import org.wildfly.extension.undertow.logging.UndertowLogger;
+import org.wildfly.security.manager.WildFlySecurityManager;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ * @author Radoslav Husar
+ */
+public class Host implements Service, FilterLocation {
+ private final PathHandler pathHandler = new PathHandler();
+ private volatile HttpHandler rootHandler = null;
+ private final Set allAliases;
+ private final String name;
+ private final String defaultWebModule;
+ private final InjectedValue server = new InjectedValue<>();
+ private final InjectedValue undertowService = new InjectedValue<>();
+ private volatile AccessLogService accessLogService;
+ private final List filters = new CopyOnWriteArrayList<>();
+ private final Set deployments = new CopyOnWriteArraySet<>();
+ private final Map locations = new CopyOnWriteMap<>();
+ private final Map additionalAuthenticationMechanisms = new ConcurrentHashMap<>();
+ private final HostRootHandler hostRootHandler = new HostRootHandler();
+ private final InjectedValue controlledProcessStateServiceInjectedValue = new InjectedValue<>();
+ private volatile GateHandlerWrapper gateHandlerWrapper;
+ private final DefaultResponseCodeHandler defaultHandler;
+ private final boolean queueRequestsOnStart;
+ private final int defaultResponseCode;
+
+ private final InjectedValue suspendControllerInjectedValue = new InjectedValue<>();
+
+
+ ServerActivity suspendListener = new ServerActivity() {
+ @Override
+ public void preSuspend(ServerActivityCallback listener) {
+ defaultHandler.setSuspended(true);
+ listener.done();
+ }
+
+ @Override
+ public void suspended(ServerActivityCallback listener) {
+ listener.done();
+ }
+
+ @Override
+ public void resume() {
+ defaultHandler.setSuspended(false);
+ }
+ };
+
+ public Host(final String name, final List aliases, final String defaultWebModule, final int defaultResponseCode, final boolean queueRequestsOnStart ) {
+ this.name = name;
+ this.defaultWebModule = defaultWebModule;
+ Set hosts = new HashSet<>(aliases.size() + 1);
+ hosts.add(name);
+ hosts.addAll(aliases);
+ allAliases = Collections.unmodifiableSet(hosts);
+ this.queueRequestsOnStart = queueRequestsOnStart;
+ this.defaultHandler = new DefaultResponseCodeHandler(defaultResponseCode);
+ this.defaultResponseCode = defaultResponseCode;
+ this.setupDefaultResponseCodeHandler();
+ }
+
+ private String getDeployedContextPath(DeploymentInfo deploymentInfo) {
+ return "".equals(deploymentInfo.getContextPath()) ? "/" : deploymentInfo.getContextPath();
+ }
+
+ @Override
+ public void start(StartContext context) throws StartException {
+ suspendControllerInjectedValue.getValue().registerActivity(suspendListener);
+ if(suspendControllerInjectedValue.getValue().getState() == SuspendController.State.RUNNING) {
+ defaultHandler.setSuspended(false);
+ } else {
+ defaultHandler.setSuspended(true);
+ }
+ ControlledProcessStateService controlledProcessStateService = controlledProcessStateServiceInjectedValue.getValue();
+ //may be null for tests
+ if(controlledProcessStateService != null && controlledProcessStateService.getCurrentState() == ControlledProcessState.State.STARTING) {
+ gateHandlerWrapper = new GateHandlerWrapper(queueRequestsOnStart ? -1 : defaultResponseCode);
+ controlledProcessStateService.addPropertyChangeListener(new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ controlledProcessStateService.removePropertyChangeListener(this);
+ if(gateHandlerWrapper != null) {
+ gateHandlerWrapper.open();
+ gateHandlerWrapper = null;
+ }
+ rootHandler = null;
+ }
+ });
+ }
+ server.getValue().registerHost(this);
+ UndertowLogger.ROOT_LOGGER.hostStarting(name);
+ }
+
+ private HttpHandler configureRootHandler() {
+ AccessLogService logService = accessLogService;
+ HttpHandler rootHandler = pathHandler;
+
+ ArrayList filters = new ArrayList<>(this.filters);
+
+ //handle options * requests
+ rootHandler = new OptionsHandler(rootHandler);
+
+ //handle requests that use the Expect: 100-continue header
+ rootHandler = Handlers.httpContinueRead(rootHandler);
+
+ rootHandler = LocationService.configureHandlerChain(rootHandler, filters);
+ if (logService != null) {
+ rootHandler = logService.configureAccessLogHandler(rootHandler);
+ }
+
+ // handle .well-known requests from ACME certificate authorities
+ String path = WildFlySecurityManager.getPropertyPrivileged("jboss.home.dir", ".");
+ Path base;
+ try {
+ base = Paths.get(path).normalize().toRealPath();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ final int cacheBufferSize = 1024;
+ final int cacheBuffers = 1024;
+ PathResourceManager resourceManager = new PathResourceManager(base, cacheBufferSize * cacheBuffers, true, false);
+ rootHandler = new AcmeResourceHandler(resourceManager, rootHandler);
+
+ GateHandlerWrapper gateHandlerWrapper = this.gateHandlerWrapper;
+ if(gateHandlerWrapper != null) {
+ rootHandler = gateHandlerWrapper.wrap(rootHandler);
+ }
+ return rootHandler;
+ }
+
+ @Override
+ public void stop(StopContext context) {
+ server.getValue().unregisterHost(this);
+ pathHandler.clearPaths();
+ if(gateHandlerWrapper != null) {
+ gateHandlerWrapper.open();
+ gateHandlerWrapper = null;
+ }
+ UndertowLogger.ROOT_LOGGER.hostStopping(name);
+ suspendControllerInjectedValue.getValue().unRegisterActivity(suspendListener);
+ }
+
+ @Override
+ public Host getValue() throws IllegalStateException, IllegalArgumentException {
+ return this;
+ }
+
+ protected InjectedValue getServerInjection() {
+ return server;
+ }
+
+ void setAccessLogService(AccessLogService service) {
+ this.accessLogService = service;
+ rootHandler = null;
+ }
+
+ public Server getServer() {
+ return server.getValue();
+ }
+
+ protected InjectedValue getUndertowService() {
+ return undertowService;
+ }
+
+ public Set getAllAliases() {
+ return allAliases;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ protected HttpHandler getRootHandler() {
+ return hostRootHandler;
+ }
+
+ List getFilters() {
+ return Collections.unmodifiableList(filters);
+ }
+
+ protected HttpHandler getOrCreateRootHandler() {
+ HttpHandler root = rootHandler;
+ if(root == null) {
+ synchronized (this) {
+ root = rootHandler;
+ if(root == null) {
+ return rootHandler = configureRootHandler();
+ }
+ }
+ }
+ return root;
+ }
+
+ public String getDefaultWebModule() {
+ return defaultWebModule;
+ }
+
+ public void registerDeployment(final Deployment deployment, HttpHandler handler) {
+ DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();
+ String path = getDeployedContextPath(deploymentInfo);
+ registerHandler(path, handler);
+ deployments.add(deployment);
+ UndertowLogger.ROOT_LOGGER.registerWebapp(path, getServer().getName());
+ undertowService.getValue().fireEvent(listener -> listener.onDeploymentStart(deployment, Host.this));
+ }
+
+ public void unregisterDeployment(final Deployment deployment) {
+ DeploymentInfo deploymentInfo = deployment.getDeploymentInfo();
+ String path = getDeployedContextPath(deploymentInfo);
+ undertowService.getValue().fireEvent(listener -> listener.onDeploymentStop(deployment, Host.this));
+ unregisterHandler(path);
+ deployments.remove(deployment);
+ UndertowLogger.ROOT_LOGGER.unregisterWebapp(path, getServer().getName());
+ }
+
+ void registerLocation(String path) {
+ String realPath = path.startsWith("/") ? path : "/" + path;
+ locations.put(realPath, null);
+ undertowService.getValue().fireEvent(listener -> listener.onDeploymentStart(realPath, Host.this));
+ }
+
+ void unregisterLocation(String path) {
+ String realPath = path.startsWith("/") ? path : "/" + path;
+ locations.remove(realPath);
+ undertowService.getValue().fireEvent(listener -> listener.onDeploymentStop(realPath, Host.this));
+ }
+
+ public void registerHandler(String path, HttpHandler handler) {
+ pathHandler.addPrefixPath(path, handler);
+ }
+
+ public void unregisterHandler(String path) {
+ pathHandler.removePrefixPath(path);
+ // if there is registered location for given path, serve it from now on
+ LocationService location = locations.get(path);
+ if (location != null) {
+ pathHandler.addPrefixPath(location.getLocationPath(), location.getLocationHandler());
+ }
+ // else serve the default response code
+ else if (path.equals("/")) {
+ this.setupDefaultResponseCodeHandler();
+ }
+ }
+
+ void registerLocation(LocationService location) {
+ locations.put(location.getLocationPath(), location);
+ registerHandler(location.getLocationPath(), location.getLocationHandler());
+ undertowService.getValue().fireEvent(listener -> listener.onDeploymentStart(location.getLocationPath(), Host.this));
+ }
+
+ void unregisterLocation(LocationService location) {
+ locations.remove(location.getLocationPath());
+ unregisterHandler(location.getLocationPath());
+ undertowService.getValue().fireEvent(listener -> listener.onDeploymentStop(location.getLocationPath(), Host.this));
+ }
+
+ public Set getLocations() {
+ return Collections.unmodifiableSet(locations.keySet());
+ }
+
+ /**
+ * @return set of currently registered {@link Deployment}s on this host
+ */
+ public Set getDeployments() {
+ return Collections.unmodifiableSet(deployments);
+ }
+
+ void registerAdditionalAuthenticationMechanism(String name, AuthenticationMechanism authenticationMechanism){
+ additionalAuthenticationMechanisms.put(name, authenticationMechanism);
+ }
+
+ void unregisterAdditionalAuthenticationMechanism(String name){
+ additionalAuthenticationMechanisms.remove(name);
+ }
+
+ public Map getAdditionalAuthenticationMechanisms() {
+ return new LinkedHashMap<>(additionalAuthenticationMechanisms);
+ }
+
+ public InjectedValue getSuspendControllerInjectedValue() {
+ return suspendControllerInjectedValue;
+ }
+
+ @Override
+ public void addFilter(UndertowFilter filterRef) {
+ filters.add(filterRef);
+ rootHandler = null;
+ }
+
+ @Override
+ public void removeFilter(UndertowFilter filterRef) {
+ filters.remove(filterRef);
+ rootHandler = null;
+ }
+
+ protected void setupDefaultResponseCodeHandler(){
+ if(this.defaultHandler != null){
+ this.registerHandler("/", this.defaultHandler);
+ }
+ }
+
+ InjectedValue getControlledProcessStateServiceInjectedValue() {
+ return controlledProcessStateServiceInjectedValue;
+ }
+
+ private static final class OptionsHandler implements HttpHandler {
+
+ private final HttpHandler next;
+
+ private OptionsHandler(HttpHandler next) {
+ this.next = next;
+ }
+
+ @Override
+ public void handleRequest(HttpServerExchange exchange) throws Exception {
+ if(exchange.getRequestMethod().equals(Methods.OPTIONS) &&
+ exchange.getRelativePath().equals("*")) {
+ //handle the OPTIONS requests
+ //basically just return an empty response
+ exchange.endExchange();
+ return;
+ }
+ next.handleRequest(exchange);
+ }
+ }
+
+ private static final class AcmeResourceHandler extends ResourceHandler {
+ private static final String ACME_CHALLENGE_REGEX = "/\\.well-known/acme-challenge/[A-Za-z0-9_-]+";
+
+ private final HttpHandler next;
+
+ private AcmeResourceHandler(ResourceManager resourceManager, HttpHandler next) {
+ super(resourceManager, next);
+ this.next = next;
+ }
+
+ @Override
+ public void handleRequest(HttpServerExchange exchange) throws Exception {
+ if (exchange.getRequestMethod().equals(Methods.GET) && exchange.getRelativePath().matches(ACME_CHALLENGE_REGEX)) {
+ super.handleRequest(exchange);
+ } else {
+ next.handleRequest(exchange);
+ }
+ }
+ }
+
+ private class HostRootHandler implements HttpHandler {
+
+ @Override
+ public void handleRequest(HttpServerExchange exchange) throws Exception {
+ getOrCreateRootHandler().handleRequest(exchange);
+ }
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostAdd.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostAdd.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostAdd.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,158 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import static org.wildfly.extension.undertow.HostDefinition.HOST_CAPABILITY;
+import static org.wildfly.extension.undertow.ServerDefinition.SERVER_CAPABILITY;
+
+import java.util.LinkedList;
+import java.util.List;
+
+import org.jboss.as.controller.AbstractAddStepHandler;
+import org.jboss.as.controller.CapabilityServiceBuilder;
+import org.jboss.as.controller.ControlledProcessStateService;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.as.controller.ProcessType;
+import org.jboss.as.controller.registry.Resource;
+import org.jboss.as.server.mgmt.UndertowHttpManagementService;
+import org.jboss.as.server.mgmt.domain.HttpManagement;
+import org.jboss.as.server.suspend.SuspendController;
+import org.jboss.as.web.host.CommonWebServer;
+import org.jboss.as.web.host.WebHost;
+import org.jboss.dmr.ModelNode;
+import org.jboss.msc.service.ServiceBuilder;
+import org.jboss.msc.service.ServiceController;
+import org.jboss.msc.service.ServiceController.Mode;
+import org.jboss.msc.service.ServiceName;
+import org.wildfly.extension.requestcontroller.RequestController;
+import org.wildfly.extension.undertow.deployment.DefaultDeploymentMappingProvider;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+class HostAdd extends AbstractAddStepHandler {
+
+ static final HostAdd INSTANCE = new HostAdd();
+
+ private HostAdd() {
+ super(HostDefinition.ALIAS, HostDefinition.DEFAULT_WEB_MODULE, HostDefinition.DEFAULT_RESPONSE_CODE, HostDefinition.DISABLE_CONSOLE_REDIRECT, HostDefinition.QUEUE_REQUESTS_ON_START);
+ }
+
+ @Override
+ protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException {
+ super.recordCapabilitiesAndRequirements(context, operation, resource);
+
+ String ourCap = HOST_CAPABILITY.getDynamicName(context.getCurrentAddress());
+ String serverCap = SERVER_CAPABILITY.getDynamicName(context.getCurrentAddress().getParent());
+ context.registerAdditionalCapabilityRequirement(serverCap, ourCap, null);
+ }
+
+ @Override
+ protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
+ final PathAddress address = context.getCurrentAddress();
+ final PathAddress serverAddress = address.getParent();
+ final PathAddress subsystemAddress = serverAddress.getParent();
+ final ModelNode subsystemModel = Resource.Tools.readModel(context.readResourceFromRoot(subsystemAddress, false), 0);
+ final ModelNode serverModel = Resource.Tools.readModel(context.readResourceFromRoot(serverAddress, false), 0);
+
+ final String name = address.getLastElement().getValue();
+ final List aliases = HostDefinition.ALIAS.unwrap(context, model);
+ final String defaultWebModule = HostDefinition.DEFAULT_WEB_MODULE.resolveModelAttribute(context, model).asString();
+ final String defaultServerName = UndertowRootDefinition.DEFAULT_SERVER.resolveModelAttribute(context, subsystemModel).asString();
+ final String defaultHostName = ServerDefinition.DEFAULT_HOST.resolveModelAttribute(context, serverModel).asString();
+ final String serverName = serverAddress.getLastElement().getValue();
+ final boolean isDefaultHost = defaultServerName.equals(serverName) && name.equals(defaultHostName);
+ final int defaultResponseCode = HostDefinition.DEFAULT_RESPONSE_CODE.resolveModelAttribute(context, model).asInt();
+ final boolean enableConsoleRedirect = !HostDefinition.DISABLE_CONSOLE_REDIRECT.resolveModelAttribute(context, model).asBoolean();
+ final boolean queueRequestsOnStart = HostDefinition.QUEUE_REQUESTS_ON_START.resolveModelAttribute(context, model).asBoolean();
+ DefaultDeploymentMappingProvider.instance().addMapping(defaultWebModule, serverName, name);
+
+ final ServiceName virtualHostServiceName = HostDefinition.HOST_CAPABILITY.fromBaseCapability(address).getCapabilityServiceName();
+
+ final Host service = new Host(name, aliases == null ? new LinkedList<>(): aliases, defaultWebModule, defaultResponseCode, queueRequestsOnStart);
+
+ final ServiceBuilder builder = context.getCapabilityServiceTarget().addCapability(HostDefinition.HOST_CAPABILITY, service)
+ .addCapabilityRequirement(Capabilities.CAPABILITY_SERVER, Server.class, service.getServerInjection(), serverName)
+ .addCapabilityRequirement(Capabilities.CAPABILITY_UNDERTOW, UndertowService.class, service.getUndertowService())
+ .addDependency(SuspendController.SERVICE_NAME, SuspendController.class, service.getSuspendControllerInjectedValue())
+ .addDependency(ControlledProcessStateService.SERVICE_NAME, ControlledProcessStateService.class, service.getControlledProcessStateServiceInjectedValue());
+
+ builder.setInitialMode(Mode.ON_DEMAND);
+
+ if (isDefaultHost) {
+ addCommonHost(context, aliases, serverName, virtualHostServiceName);
+ builder.addAliases(UndertowService.DEFAULT_HOST);//add alias for default host of default server service
+ }
+ //this is workaround for a bit so old service names still work!
+ builder.addAliases(UndertowService.virtualHostName(serverName, name));
+ builder.install();
+
+ if (enableConsoleRedirect) {
+ // Setup the web console redirect
+ final ServiceName consoleRedirectName = UndertowService.consoleRedirectServiceName(serverName, name);
+ // A standalone server is the only process type with a console redirect
+ if (context.getProcessType() == ProcessType.STANDALONE_SERVER) {
+ final ConsoleRedirectService redirectService = new ConsoleRedirectService();
+ final ServiceBuilder redirectBuilder = context.getServiceTarget().addService(consoleRedirectName, redirectService)
+ .addDependency(UndertowHttpManagementService.SERVICE_NAME, HttpManagement.class, redirectService.getHttpManagementInjector())
+ .addDependency(virtualHostServiceName, Host.class, redirectService.getHostInjector())
+ .setInitialMode(Mode.PASSIVE);
+ redirectBuilder.install();
+ } else {
+ // Other process types don't have a console, not depending on the UndertowHttpManagementService should
+ // result in a null dependency in the service and redirect accordingly
+ final ConsoleRedirectService redirectService = new ConsoleRedirectService();
+ final ServiceBuilder redirectBuilder = context.getServiceTarget().addService(consoleRedirectName, redirectService)
+ .addDependency(virtualHostServiceName, Host.class, redirectService.getHostInjector())
+ .setInitialMode(Mode.PASSIVE);
+ redirectBuilder.install();
+ }
+ }
+ }
+
+ private ServiceController addCommonHost(OperationContext context, List aliases,
+ String serverName, ServiceName virtualHostServiceName) {
+ WebHostService service = new WebHostService();
+ final CapabilityServiceBuilder builder = context.getCapabilityServiceTarget()
+ .addCapability(WebHost.CAPABILITY, service)
+ .addCapabilityRequirement(Capabilities.CAPABILITY_SERVER, Server.class, service.getServer(), serverName)
+ .addCapabilityRequirement(CommonWebServer.CAPABILITY_NAME, CommonWebServer.class)
+ .addDependency(virtualHostServiceName, Host.class, service.getHost());
+
+ if(context.hasOptionalCapability(Capabilities.REF_REQUEST_CONTROLLER, null, null)) {
+ builder.addCapabilityRequirement(Capabilities.REF_REQUEST_CONTROLLER, RequestController.class, service.getRequestControllerInjectedValue());
+ }
+
+ builder.addAliases(WebHost.SERVICE_NAME.append(context.getCurrentAddressValue()));
+ if (aliases != null) {
+ for (String alias : aliases) {
+ builder.addAliases(WebHost.SERVICE_NAME.append(alias));
+ }
+ }
+
+ builder.setInitialMode(Mode.PASSIVE);
+ return builder.install();
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,123 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+import org.jboss.as.controller.AttributeDefinition;
+import org.jboss.as.controller.AttributeMarshaller;
+import org.jboss.as.controller.AttributeParser;
+import org.jboss.as.controller.PersistentResourceDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinition;
+import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
+import org.jboss.as.controller.StringListAttributeDefinition;
+import org.jboss.as.controller.capability.RuntimeCapability;
+import org.jboss.as.controller.operations.validation.IntRangeValidator;
+import org.jboss.as.controller.operations.validation.StringLengthValidator;
+import org.jboss.as.controller.registry.AttributeAccess;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+import org.jboss.as.web.host.WebHost;
+import org.jboss.dmr.ModelNode;
+import org.jboss.dmr.ModelType;
+import org.wildfly.extension.undertow.filters.FilterRefDefinition;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+class HostDefinition extends PersistentResourceDefinition {
+
+ static final RuntimeCapability HOST_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_HOST, true, Host.class)
+ .addRequirements(Capabilities.CAPABILITY_UNDERTOW)
+ //addDynamicRequirements(Capabilities.CAPABILITY_SERVER) -- has no function so don't use it
+ .setDynamicNameMapper(pathElements -> new String[]{
+ pathElements.getParent().getLastElement().getValue(),
+ pathElements.getLastElement().getValue()})
+ .build();
+
+
+ static final StringListAttributeDefinition ALIAS = new StringListAttributeDefinition.Builder(Constants.ALIAS)
+ .setRequired(false)
+ .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES)
+ .setElementValidator(new StringLengthValidator(1))
+ .setAllowExpression(true)
+ .setAttributeParser(AttributeParser.COMMA_DELIMITED_STRING_LIST)
+ .setAttributeMarshaller(AttributeMarshaller.COMMA_STRING_LIST)
+ .build();
+ static final SimpleAttributeDefinition DEFAULT_WEB_MODULE = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_WEB_MODULE, ModelType.STRING, true)
+ .setRestartAllServices()
+ .setValidator(new StringLengthValidator(1, true, false))
+ .setDefaultValue(new ModelNode("ROOT.war"))
+ .build();
+
+ static final SimpleAttributeDefinition DEFAULT_RESPONSE_CODE = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_RESPONSE_CODE, ModelType.INT, true)
+ .setRestartAllServices()
+ .setValidator(new IntRangeValidator(400, 599, true, true))
+ .setDefaultValue(new ModelNode(404))
+ .setAllowExpression(true)
+ .build();
+ static final SimpleAttributeDefinition DISABLE_CONSOLE_REDIRECT = new SimpleAttributeDefinitionBuilder("disable-console-redirect", ModelType.BOOLEAN, true)
+ .setRestartAllServices()
+ .setDefaultValue(new ModelNode(false))
+ .setAllowExpression(true)
+ .build();
+ static final SimpleAttributeDefinition QUEUE_REQUESTS_ON_START = new SimpleAttributeDefinitionBuilder("queue-requests-on-start", ModelType.BOOLEAN, true)
+ .setRestartAllServices()
+ .setDefaultValue(new ModelNode(true))
+ .setAllowExpression(true)
+ .build();
+
+ static final HostDefinition INSTANCE = new HostDefinition();
+ private static final Collection ATTRIBUTES = Collections.unmodifiableCollection(Arrays.asList(ALIAS, DEFAULT_WEB_MODULE, DEFAULT_RESPONSE_CODE, DISABLE_CONSOLE_REDIRECT, QUEUE_REQUESTS_ON_START));
+ private static final List extends PersistentResourceDefinition> CHILDREN = Collections.unmodifiableList(Arrays.asList(
+ LocationDefinition.INSTANCE,
+ AccessLogDefinition.INSTANCE,
+ FilterRefDefinition.INSTANCE,
+ HttpInvokerDefinition.INSTANCE,
+ new HostSingleSignOnDefinition()
+ ));
+
+ private HostDefinition() {
+ super(UndertowExtension.HOST_PATH, UndertowExtension.getResolver(Constants.HOST),
+ HostAdd.INSTANCE,
+ new HostRemove());
+ }
+
+ @Override
+ public Collection getAttributes() {
+ return ATTRIBUTES;
+ }
+
+ @Override
+ public List extends PersistentResourceDefinition> getChildren() {
+ return CHILDREN;
+ }
+
+ @Override
+ public void registerCapabilities(ManagementResourceRegistration resourceRegistration) {
+ resourceRegistration.registerCapability(HOST_CAPABILITY);
+ resourceRegistration.registerCapability(WebHost.CAPABILITY);
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostRemove.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostRemove.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostRemove.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,62 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import org.jboss.as.controller.AbstractRemoveStepHandler;
+import org.jboss.as.controller.OperationContext;
+import org.jboss.as.controller.OperationFailedException;
+import org.jboss.as.controller.PathAddress;
+import org.jboss.as.web.host.WebHost;
+import org.jboss.dmr.ModelNode;
+import org.jboss.msc.service.ServiceName;
+import org.wildfly.extension.undertow.deployment.DefaultDeploymentMappingProvider;
+
+/**
+ * @author Tomaz Cerar (c) 2013 Red Hat Inc.
+ */
+class HostRemove extends AbstractRemoveStepHandler {
+
+ @Override
+ protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
+ final PathAddress address = context.getCurrentAddress();
+ final PathAddress parent = address.getParent();
+ final String name = address.getLastElement().getValue();
+ final String serverName = parent.getLastElement().getValue();
+ final ServiceName virtualHostServiceName = HostDefinition.HOST_CAPABILITY.getCapabilityServiceName(serverName, name);
+ context.removeService(virtualHostServiceName);
+ final ServiceName consoleRedirectName = UndertowService.consoleRedirectServiceName(serverName, name);
+ context.removeService(consoleRedirectName);
+ final ServiceName commonHostName = WebHost.SERVICE_NAME.append(name);
+ context.removeService(commonHostName);
+ final String defaultWebModule = HostDefinition.DEFAULT_WEB_MODULE.resolveModelAttribute(context, model).asString();
+ DefaultDeploymentMappingProvider.instance().removeMapping(defaultWebModule);
+ }
+
+ protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException {
+ if (context.isResourceServiceRestartAllowed()) {
+ HostAdd.INSTANCE.performRuntime(context, operation, model);
+ } else {
+ context.revertReloadRequired();
+ }
+ }
+}
Index: 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostSingleSignOnDefinition.java
===================================================================
diff -u
--- 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostSingleSignOnDefinition.java (revision 0)
+++ 3rdParty_sources/undertow/org/wildfly/extension/undertow/HostSingleSignOnDefinition.java (revision 7888422dedc5a048743723a09465df0a3d0d201b)
@@ -0,0 +1,50 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2017, Red Hat, Inc., and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.wildfly.extension.undertow;
+
+import org.jboss.as.clustering.controller.ResourceDescriptor;
+import org.jboss.as.clustering.controller.SimpleResourceRegistration;
+import org.jboss.as.controller.capability.RuntimeCapability;
+import org.jboss.as.controller.registry.ManagementResourceRegistration;
+/**
+ * @author Paul Ferraro
+ */
+public class HostSingleSignOnDefinition extends SingleSignOnDefinition {
+
+ //we use a runtime API of Object as a hack, so we can check for the presence of the capability in a DUP
+ public static final RuntimeCapability