repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AccessLogService.java
/* * 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.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; import java.util.function.Consumer; import java.util.function.Supplier; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class AccessLogService implements Service<AccessLogService> { private final Consumer<AccessLogService> serviceConsumer; private final Supplier<Host> host; private final Supplier<XnioWorker> worker; private final Supplier<PathManager> pathManager; 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; AccessLogService(final Consumer<AccessLogService> serviceConsumer, final Supplier<Host> host, final Supplier<XnioWorker> worker, final Supplier<PathManager> pathManager, final String pattern, final boolean extended, final Predicate predicate) { this(serviceConsumer, host, worker, pathManager, pattern, null, null, null, null, false, extended, true, predicate); } AccessLogService(final Consumer<AccessLogService> serviceConsumer, final Supplier<Host> host, final Supplier<XnioWorker> worker, final Supplier<PathManager> pathManager, final String pattern, final String path, final String pathRelativeTo, final String filePrefix, final String fileSuffix, final boolean rotate, final boolean extended, final boolean useServerLog, final Predicate predicate) { this.serviceConsumer = serviceConsumer; this.host = host; this.worker = worker; this.pathManager = pathManager; this.pattern = pattern; this.path = path; this.pathRelativeTo = pathRelativeTo; this.filePrefix = filePrefix; this.fileSuffix = fileSuffix; this.rotate = rotate; this.extended = extended; this.useServerLog = useServerLog; 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.get().registerCallback(pathRelativeTo, PathManager.ReloadServerCallback.create(), PathManager.Event.UPDATED, PathManager.Event.REMOVED); } directory = Paths.get(pathManager.get().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.get()) .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.get().setAccessLogService(this); serviceConsumer.accept(this); } @Override public void stop(StopContext context) { serviceConsumer.accept(null); host.get().setAccessLogService(null); if (callbackHandle != null) { callbackHandle.remove(); callbackHandle = null; } if( logReceiver instanceof DefaultAccessLogReceiver ) { IoUtils.safeClose((DefaultAccessLogReceiver) logReceiver); } logReceiver = null; } 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); } } boolean isRotate() { return rotate; } String getPath() { return path; } @Override public AccessLogService getValue() throws IllegalStateException, IllegalArgumentException { return this; } }
7,263
41.232558
181
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AffinityCookieDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, 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.EnumSet; import java.util.stream.Collectors; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.dmr.ModelNode; /** * Resource description for the affinity cookie configuration with cookie name being required and no comment being defined. * * @author Radoslav Husar */ class AffinityCookieDefinition extends AbstractCookieDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.AFFINITY_COOKIE); static final Collection<AttributeDefinition> ATTRIBUTES = EnumSet.complementOf(EnumSet.of(Attribute.OPTIONAL_NAME, Attribute.COMMENT)) .stream().map(Attribute::getDefinition).collect(Collectors.toUnmodifiableSet()); AffinityCookieDefinition() { super(PATH_ELEMENT, ATTRIBUTES); } static CookieConfig getConfig(final ExpressionResolver context, final ModelNode model) throws OperationFailedException { return AbstractCookieDefinition.getConfig(Attribute.REQUIRED_NAME, context, model); } }
2,278
39.696429
138
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ListenerAdd.java
/* * 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_IO_WORKER; import static org.wildfly.extension.undertow.Capabilities.REF_SOCKET_BINDING; import static org.wildfly.extension.undertow.ListenerResourceDefinition.LISTENER_CAPABILITY; import static org.wildfly.extension.undertow.ServerDefinition.SERVER_CAPABILITY; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Consumer; import io.undertow.connector.ByteBufferPool; import io.undertow.server.handlers.DisallowedMethodsHandler; import io.undertow.server.handlers.PeerNameResolvingHandler; import io.undertow.servlet.handlers.MarkSecureHandler; import io.undertow.util.HttpString; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; 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.registry.Resource; import org.jboss.as.network.SocketBinding; import org.jboss.dmr.ModelNode; import org.wildfly.extension.io.OptionList; import org.xnio.OptionMap; import org.xnio.XnioWorker; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ abstract class ListenerAdd<S extends ListenerService> extends AbstractAddStepHandler { ListenerAdd(Collection<AttributeDefinition> attributes) { super(attributes); } @Override protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { super.recordCapabilitiesAndRequirements(context, operation, resource); String ourCap = LISTENER_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 parent = address.getParent(); final String name = context.getCurrentAddressValue(); final String bindingRef = ListenerResourceDefinition.SOCKET_BINDING.resolveModelAttribute(context, model).asString(); final String workerName = ListenerResourceDefinition.WORKER.resolveModelAttribute(context, model).asString(); final String bufferPoolName = ListenerResourceDefinition.BUFFER_POOL.resolveModelAttribute(context, model).asString(); final boolean enabled = ListenerResourceDefinition.ENABLED.resolveModelAttribute(context, model).asBoolean(); final boolean peerHostLookup = ListenerResourceDefinition.RESOLVE_PEER_ADDRESS.resolveModelAttribute(context, model).asBoolean(); final boolean secure = ListenerResourceDefinition.SECURE.resolveModelAttribute(context, model).asBoolean(); OptionMap listenerOptions = OptionList.resolveOptions(context, model, ListenerResourceDefinition.LISTENER_OPTIONS); OptionMap socketOptions = OptionList.resolveOptions(context, model, ListenerResourceDefinition.SOCKET_OPTIONS); String serverName = parent.getLastElement().getValue(); final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(ListenerResourceDefinition.LISTENER_CAPABILITY); final Consumer<ListenerService> serviceConsumer = sb.provides(ListenerResourceDefinition.LISTENER_CAPABILITY, UndertowService.listenerName(name)); final S service = createService(serviceConsumer, name, serverName, context, model, listenerOptions,socketOptions); if (peerHostLookup) { service.addWrapperHandler(PeerNameResolvingHandler::new); } service.setEnabled(enabled); if(secure) { service.addWrapperHandler(MarkSecureHandler.WRAPPER); } List<String> disallowedMethods = ListenerResourceDefinition.DISALLOWED_METHODS.unwrap(context, model); if(!disallowedMethods.isEmpty()) { final Set<HttpString> methodSet = new HashSet<>(); for (String i : disallowedMethods) { HttpString httpString = new HttpString(i.trim()); methodSet.add(httpString); } service.addWrapperHandler(handler -> new DisallowedMethodsHandler(handler, methodSet)); } sb.setInstance(service); service.getWorker().set(sb.requiresCapability(REF_IO_WORKER, XnioWorker.class, workerName)); service.getBinding().set(sb.requiresCapability(REF_SOCKET_BINDING, SocketBinding.class, bindingRef)); service.getBufferPool().set(sb.requiresCapability(Capabilities.CAPABILITY_BYTE_BUFFER_POOL, ByteBufferPool.class, bufferPoolName)); service.getServerService().set(sb.requiresCapability(Capabilities.CAPABILITY_SERVER, Server.class, serverName)); configureAdditionalDependencies(context, sb, model, service); sb.install(); } abstract S createService(final Consumer<ListenerService> serviceConsumer, final String name, final String serverName, final OperationContext context, ModelNode model, OptionMap listenerOptions, OptionMap socketOptions) throws OperationFailedException; abstract void configureAdditionalDependencies(OperationContext context, CapabilityServiceBuilder<?> serviceBuilder, ModelNode model, S service) throws OperationFailedException; }
6,794
54.696721
255
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowFilter.java
/* * 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.HandlerWrapper; /** * @author Stuart Douglas */ public interface UndertowFilter extends HandlerWrapper { int getPriority(); }
1,225
35.058824
70
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AbstractCookieDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, 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.function.UnaryOperator; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.RestartParentResourceAddHandler; import org.jboss.as.controller.RestartParentResourceRemoveHandler; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceName; /** * Resource definition for a Cookie configuration. * * @author Radoslav Husar */ abstract class AbstractCookieDefinition extends PersistentResourceDefinition { enum Attribute implements org.jboss.as.clustering.controller.Attribute { OPTIONAL_NAME(Constants.NAME, ModelType.STRING), REQUIRED_NAME(Constants.NAME, ModelType.STRING, ad -> ad.setRequired(true)), DOMAIN(Constants.DOMAIN, ModelType.STRING), COMMENT(Constants.COMMENT, ModelType.STRING, ad -> ad.setDeprecated(UndertowSubsystemModel.VERSION_13_0_0.getVersion())), HTTP_ONLY(Constants.HTTP_ONLY, ModelType.BOOLEAN), SECURE(Constants.SECURE, ModelType.BOOLEAN), MAX_AGE(Constants.MAX_AGE, ModelType.INT), ; private final AttributeDefinition definition; Attribute(String name, ModelType type) { this(name, type, UnaryOperator.identity()); } Attribute(String name, ModelType type, UnaryOperator<SimpleAttributeDefinitionBuilder> builder) { this.definition = builder.apply(new SimpleAttributeDefinitionBuilder(name, type) .setRequired(false) .setRestartAllServices() .setAllowExpression(true) ).build(); } @Override public AttributeDefinition getDefinition() { return this.definition; } } Collection<AttributeDefinition> attributes; public AbstractCookieDefinition(PathElement path, Collection<AttributeDefinition> attributes) { super(path, UndertowExtension.getResolver(path.getKeyValuePair()), new SessionCookieAdd(attributes), new SessionCookieRemove() ); this.attributes = attributes; } @Override public Collection<AttributeDefinition> getAttributes() { return attributes; } static CookieConfig getConfig(final Attribute nameAttribute, final ExpressionResolver context, final ModelNode model) throws OperationFailedException { if (!model.isDefined()) { return null; } ModelNode nameValue = nameAttribute.getDefinition().resolveModelAttribute(context, model); ModelNode domainValue = Attribute.DOMAIN.resolveModelAttribute(context, model); ModelNode secureValue = Attribute.SECURE.resolveModelAttribute(context, model); ModelNode httpOnlyValue = Attribute.HTTP_ONLY.resolveModelAttribute(context, model); ModelNode maxAgeValue = Attribute.MAX_AGE.resolveModelAttribute(context, model); final String name = nameValue.isDefined() ? nameValue.asString() : null; final String domain = domainValue.isDefined() ? domainValue.asString() : null; final Boolean secure = secureValue.isDefined() ? secureValue.asBoolean() : null; final Boolean httpOnly = httpOnlyValue.isDefined() ? httpOnlyValue.asBoolean() : null; final Integer maxAge = maxAgeValue.isDefined() ? maxAgeValue.asInt() : null; return new CookieConfig(name, domain, httpOnly, secure, maxAge); } private static class SessionCookieAdd extends RestartParentResourceAddHandler { private final Collection<AttributeDefinition> attributes; protected SessionCookieAdd(Collection<AttributeDefinition> attributes) { super(ServletContainerDefinition.PATH_ELEMENT.getKey()); this.attributes = attributes; } @Override protected void populateModel(ModelNode operation, ModelNode model) throws OperationFailedException { for (AttributeDefinition def : this.attributes) { def.validateAndSet(operation, model); } } @Override protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException { ServletContainerAdd.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY.getCapabilityServiceName(parentAddress); } } private static class SessionCookieRemove extends RestartParentResourceRemoveHandler { protected SessionCookieRemove() { super(ServletContainerDefinition.PATH_ELEMENT.getKey()); } @Override protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException { ServletContainerAdd.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY.getCapabilityServiceName(parentAddress); } } }
6,826
42.208861
155
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AccessLogAdd.java
/* * 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.xnio.XnioWorker; import java.util.function.Consumer; import java.util.function.Supplier; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final 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 String serverName = serverAddress.getLastElement().getValue(); final String hostName = hostAddress.getLastElement().getValue(); final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(AccessLogDefinition.ACCESS_LOG_CAPABILITY); final Consumer<AccessLogService> sConsumer = sb.provides(AccessLogDefinition.ACCESS_LOG_CAPABILITY, UndertowService.accessLogServiceName(serverName, hostName)); final Supplier<Host> hSupplier = sb.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverName, hostName); final Supplier<XnioWorker> wSupplier = sb.requiresCapability(Capabilities.REF_IO_WORKER, XnioWorker.class, worker); final Supplier<PathManager> pmSupplier = sb.requires(PathManagerService.SERVICE_NAME); final AccessLogService service; if (useServerLog) { service = new AccessLogService(sConsumer, hSupplier, wSupplier, pmSupplier, pattern, extended, predicate); } else { service = new AccessLogService(sConsumer, hSupplier, wSupplier, pmSupplier, pattern, directory, relativeTo, filePrefix, fileSuffix, rotate, extended, false, predicate); } sb.setInstance(service); sb.install(); } }
5,031
53.695652
180
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/SingleSignOnDefinition.java
/* * 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 org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> 2014 Red Hat Inc. * @author Paul Ferraro */ class SingleSignOnDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.SINGLE_SIGN_ON); enum Attribute implements org.jboss.as.clustering.controller.Attribute { DOMAIN(Constants.DOMAIN, ModelType.STRING, null), PATH("path", ModelType.STRING, new ModelNode("/")), HTTP_ONLY("http-only", ModelType.BOOLEAN, ModelNode.FALSE), SECURE("secure", ModelType.BOOLEAN, ModelNode.FALSE), COOKIE_NAME("cookie-name", ModelType.STRING, new ModelNode("JSESSIONIDSSO")), ; private final AttributeDefinition definition; Attribute(String name, ModelType type, ModelNode defaultValue) { this.definition = new SimpleAttributeDefinitionBuilder(name, type) .setRequired(false) .setAllowExpression(true) .setDefaultValue(defaultValue) .setRestartAllServices() .build(); } @Override public AttributeDefinition getDefinition() { return this.definition; } } SingleSignOnDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getValue()))); } @Override public Collection<AttributeDefinition> getAttributes() { // Attributes will be registered by the parent implementation return Collections.emptyList(); } }
3,101
39.815789
125
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HostDefinition.java
/* * 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.List; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeMarshaller; import org.jboss.as.controller.AttributeParser; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.capability.DynamicNameMappers; 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.web.host.WebHost; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.filters.FilterRefDefinition; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ class HostDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.HOST); public static final String DEFAULT_WEB_MODULE_DEFAULT = "ROOT.war"; static final RuntimeCapability<Void> 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(DynamicNameMappers.PARENT) .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(DEFAULT_WEB_MODULE_DEFAULT)) .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(ModelNode.FALSE) .setAllowExpression(true) .build(); static final SimpleAttributeDefinition QUEUE_REQUESTS_ON_START = new SimpleAttributeDefinitionBuilder("queue-requests-on-start", ModelType.BOOLEAN, true) .setRestartAllServices() .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of(ALIAS, DEFAULT_WEB_MODULE, DEFAULT_RESPONSE_CODE, DISABLE_CONSOLE_REDIRECT, QUEUE_REQUESTS_ON_START); HostDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey())) .setAddHandler(HostAdd.INSTANCE) .setRemoveHandler(new HostRemove()) .addCapabilities(HOST_CAPABILITY, WebHost.CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } @Override public List<? extends PersistentResourceDefinition> getChildren() { return List.of( new LocationDefinition(), new AccessLogDefinition(), new ConsoleAccessLogDefinition(), new FilterRefDefinition(), new HttpInvokerDefinition(), new HostSingleSignOnDefinition()); } }
5,648
46.470588
171
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/MimeMappingDefinition.java
/* * 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.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredAddStepHandler; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.dmr.ModelType; import java.util.Collection; import java.util.List; /** * Global mime mapping config for file types * * @author Stuart Douglas */ class MimeMappingDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.MIME_MAPPING); protected static final SimpleAttributeDefinition VALUE = new SimpleAttributeDefinitionBuilder(Constants.VALUE, ModelType.STRING, false) .setRestartAllServices() .setAllowExpression(true) .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of(VALUE); MimeMappingDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey())) .setAddHandler(new ReloadRequiredAddStepHandler(ATTRIBUTES)) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } }
2,643
38.462687
121
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpsListenerResourceDefinition.java
/* * 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_SSL_CONTEXT; import static org.xnio.Options.SSL_CLIENT_AUTH_MODE; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import io.undertow.UndertowOptions; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelVersion; 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.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.operations.validation.EnumValidator; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.io.OptionAttributeDefinition; import org.xnio.Options; import org.xnio.SslClientAuthMode; /** * An extension to the {@see HttpListenerResourceDefinition} to allow a security-realm to be associated to obtain a pre-defined * SSLContext. * * @author <a href="mailto:[email protected]">Darran Lofthouse</a> */ public class HttpsListenerResourceDefinition extends AbstractHttpListenerResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.HTTPS_LISTENER); protected static final SimpleAttributeDefinition SSL_CONTEXT = new SimpleAttributeDefinitionBuilder(Constants.SSL_CONTEXT, ModelType.STRING, false) .setAlternatives(Constants.SECURITY_REALM, Constants.VERIFY_CLIENT, Constants.ENABLED_CIPHER_SUITES, Constants.ENABLED_PROTOCOLS, Constants.SSL_SESSION_CACHE_SIZE, Constants.SSL_SESSION_TIMEOUT) .setCapabilityReference(LISTENER_CAPABILITY, REF_SSL_CONTEXT) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1)) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SSL_REF) .build(); protected static final SimpleAttributeDefinition SECURITY_REALM = new SimpleAttributeDefinitionBuilder(Constants.SECURITY_REALM, ModelType.STRING, false) .setAlternatives(Constants.SSL_CONTEXT) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1)) .setDeprecated(ModelVersion.create(4, 0, 0)) .setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SECURITY_REALM_REF) .build(); protected static final OptionAttributeDefinition VERIFY_CLIENT = OptionAttributeDefinition.builder(Constants.VERIFY_CLIENT, SSL_CLIENT_AUTH_MODE) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setValidator(EnumValidator.create(SslClientAuthMode.class)) .setDefaultValue(new ModelNode(SslClientAuthMode.NOT_REQUESTED.name())) .setDeprecated(ModelVersion.create(4, 0, 0)) .setAlternatives(Constants.SSL_CONTEXT) .build(); protected static final OptionAttributeDefinition ENABLED_CIPHER_SUITES = OptionAttributeDefinition.builder(Constants.ENABLED_CIPHER_SUITES, Options.SSL_ENABLED_CIPHER_SUITES) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDeprecated(ModelVersion.create(4, 0, 0)) .setAlternatives(Constants.SSL_CONTEXT) .build(); protected static final OptionAttributeDefinition ENABLED_PROTOCOLS = OptionAttributeDefinition.builder(Constants.ENABLED_PROTOCOLS, Options.SSL_ENABLED_PROTOCOLS) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDeprecated(ModelVersion.create(4, 0, 0)) .setAlternatives(Constants.SSL_CONTEXT) .build(); protected static final OptionAttributeDefinition ENABLE_SPDY = OptionAttributeDefinition.builder(Constants.ENABLE_SPDY, UndertowOptions.ENABLE_SPDY) .setRequired(false) .setDeprecated(ModelVersion.create(3, 2)) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); public static final OptionAttributeDefinition SSL_SESSION_CACHE_SIZE = OptionAttributeDefinition.builder(Constants.SSL_SESSION_CACHE_SIZE, Options.SSL_SERVER_SESSION_CACHE_SIZE) .setDeprecated(ModelVersion.create(4, 0, 0)).setRequired(false).setAllowExpression(true) .setAlternatives(Constants.SSL_CONTEXT).build(); public static final OptionAttributeDefinition SSL_SESSION_TIMEOUT = OptionAttributeDefinition.builder(Constants.SSL_SESSION_TIMEOUT, Options.SSL_SERVER_SESSION_TIMEOUT) .setDeprecated(ModelVersion.create(4, 0, 0)).setMeasurementUnit(MeasurementUnit.SECONDS).setRequired(false).setAllowExpression(true).setAlternatives(Constants.SSL_CONTEXT).build(); static final List<AttributeDefinition> ATTRIBUTES = List.of(SSL_CONTEXT, SECURITY_REALM, VERIFY_CLIENT, ENABLED_CIPHER_SUITES, ENABLED_PROTOCOLS, ENABLE_SPDY, SSL_SESSION_CACHE_SIZE, SSL_SESSION_TIMEOUT); HttpsListenerResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(Constants.LISTENER)) .setCapabilities(HTTP_UPGRADE_REGISTRY_CAPABILITY), HttpsListenerAdd::new); } @Override public Collection<AttributeDefinition> getAttributes() { Collection<AttributeDefinition> attributes = new ArrayList<>(ListenerResourceDefinition.ATTRIBUTES.size() + AbstractHttpListenerResourceDefinition.ATTRIBUTES.size() + ATTRIBUTES.size()); attributes.addAll(ListenerResourceDefinition.ATTRIBUTES); attributes.addAll(AbstractHttpListenerResourceDefinition.ATTRIBUTES); attributes.addAll(ATTRIBUTES); return Collections.unmodifiableCollection(attributes); } }
7,359
54.757576
208
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/JspDefinition.java
/* * 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.AttributeDefinition; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; 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.SimpleResourceDefinition; import org.jboss.as.controller.operations.validation.ModelTypeValidator; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.as.controller.registry.AttributeAccess; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceName; import java.util.Collection; import java.util.List; /** * @author Tomaz Cerar * @created 23.2.12 18:47 */ class JspDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.JSP); protected static final SimpleAttributeDefinition DEVELOPMENT = new SimpleAttributeDefinitionBuilder(Constants.DEVELOPMENT, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition DISABLED = new SimpleAttributeDefinitionBuilder(Constants.DISABLED, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition KEEP_GENERATED = new SimpleAttributeDefinitionBuilder(Constants.KEEP_GENERATED, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition TRIM_SPACES = new SimpleAttributeDefinitionBuilder(Constants.TRIM_SPACES, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition TAG_POOLING = new SimpleAttributeDefinitionBuilder(Constants.TAG_POOLING, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition MAPPED_FILE = new SimpleAttributeDefinitionBuilder(Constants.MAPPED_FILE, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition CHECK_INTERVAL = new SimpleAttributeDefinitionBuilder(Constants.CHECK_INTERVAL, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.ZERO) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition MODIFICATION_TEST_INTERVAL = new SimpleAttributeDefinitionBuilder(Constants.MODIFICATION_TEST_INTERVAL, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(new ModelNode(4)) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition RECOMPILE_ON_FAIL = new SimpleAttributeDefinitionBuilder(Constants.RECOMPILE_ON_FAIL, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition SMAP = new SimpleAttributeDefinitionBuilder(Constants.SMAP, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition DUMP_SMAP = new SimpleAttributeDefinitionBuilder(Constants.DUMP_SMAP, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition GENERATE_STRINGS_AS_CHAR_ARRAYS = new SimpleAttributeDefinitionBuilder(Constants.GENERATE_STRINGS_AS_CHAR_ARRAYS, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition ERROR_ON_USE_BEAN_INVALID_CLASS_ATTRIBUTE = new SimpleAttributeDefinitionBuilder(Constants.ERROR_ON_USE_BEAN_INVALID_CLASS_ATTRIBUTE, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition SCRATCH_DIR = new SimpleAttributeDefinitionBuilder(Constants.SCRATCH_DIR, ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1, true)) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition SOURCE_VM = new SimpleAttributeDefinitionBuilder(Constants.SOURCE_VM, ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1, true)) .setDefaultValue(new ModelNode("1.8")) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition TARGET_VM = new SimpleAttributeDefinitionBuilder(Constants.TARGET_VM, ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1, true)) .setDefaultValue(new ModelNode("1.8")) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition JAVA_ENCODING = new SimpleAttributeDefinitionBuilder(Constants.JAVA_ENCODING, ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1, true)) .setDefaultValue(new ModelNode("UTF8")) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition X_POWERED_BY = new SimpleAttributeDefinitionBuilder(Constants.X_POWERED_BY, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new ModelTypeValidator(ModelType.BOOLEAN, true)) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition DISPLAY_SOURCE_FRAGMENT = new SimpleAttributeDefinitionBuilder(Constants.DISPLAY_SOURCE_FRAGMENT, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new ModelTypeValidator(ModelType.BOOLEAN, true)) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition OPTIMIZE_SCRIPTLETS = new SimpleAttributeDefinitionBuilder(Constants.OPTIMIZE_SCRIPTLETS, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new ModelTypeValidator(ModelType.BOOLEAN, true)) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of( // IMPORTANT -- keep these in xsd order as this order controls marshalling DISABLED, DEVELOPMENT, KEEP_GENERATED, TRIM_SPACES, TAG_POOLING, MAPPED_FILE, CHECK_INTERVAL, MODIFICATION_TEST_INTERVAL, RECOMPILE_ON_FAIL, SMAP, DUMP_SMAP, GENERATE_STRINGS_AS_CHAR_ARRAYS, ERROR_ON_USE_BEAN_INVALID_CLASS_ATTRIBUTE, SCRATCH_DIR, SOURCE_VM, TARGET_VM, JAVA_ENCODING, X_POWERED_BY, DISPLAY_SOURCE_FRAGMENT, OPTIMIZE_SCRIPTLETS); JspDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKeyValuePair())) .setAddHandler(new JSPAdd()) .setRemoveHandler(new JSPRemove()) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static JSPConfig getConfig(final ExpressionResolver context, final ModelNode model) throws OperationFailedException { if (!model.isDefined()) { return null; } boolean disabled = DISABLED.resolveModelAttribute(context, model).asBoolean(); boolean development = DEVELOPMENT.resolveModelAttribute(context, model).asBoolean(); boolean keepGenerated = KEEP_GENERATED.resolveModelAttribute(context, model).asBoolean(); boolean trimSpaces = TRIM_SPACES.resolveModelAttribute(context, model).asBoolean(); boolean tagPooling = TAG_POOLING.resolveModelAttribute(context, model).asBoolean(); boolean mappedFile = MAPPED_FILE.resolveModelAttribute(context, model).asBoolean(); int checkInterval = CHECK_INTERVAL.resolveModelAttribute(context, model).asInt(); int modificationTestInterval = MODIFICATION_TEST_INTERVAL.resolveModelAttribute(context, model).asInt(); boolean recompileOnFile = RECOMPILE_ON_FAIL.resolveModelAttribute(context, model).asBoolean(); boolean snap = SMAP.resolveModelAttribute(context, model).asBoolean(); boolean dumpSnap = DUMP_SMAP.resolveModelAttribute(context, model).asBoolean(); boolean generateStringsAsCharArrays = GENERATE_STRINGS_AS_CHAR_ARRAYS.resolveModelAttribute(context, model).asBoolean(); boolean errorOnUseBeanInvalidClassAttribute = ERROR_ON_USE_BEAN_INVALID_CLASS_ATTRIBUTE.resolveModelAttribute(context, model).asBoolean(); final ModelNode scratchDirValue = SCRATCH_DIR.resolveModelAttribute(context, model); String scratchDir = scratchDirValue.isDefined() ? scratchDirValue.asString() : null; String sourceVm = SOURCE_VM.resolveModelAttribute(context, model).asString(); String targetVm = TARGET_VM.resolveModelAttribute(context, model).asString(); String javaEncoding = JAVA_ENCODING.resolveModelAttribute(context, model).asString(); boolean xPoweredBy = X_POWERED_BY.resolveModelAttribute(context, model).asBoolean(); boolean displaySourceFragment = DISPLAY_SOURCE_FRAGMENT.resolveModelAttribute(context, model).asBoolean(); boolean optimizeScriptlets = OPTIMIZE_SCRIPTLETS.resolveModelAttribute(context, model).asBoolean(); return new JSPConfig(development, disabled, keepGenerated, trimSpaces, tagPooling, mappedFile, checkInterval, modificationTestInterval, recompileOnFile, snap, dumpSnap, generateStringsAsCharArrays, errorOnUseBeanInvalidClassAttribute, scratchDir, sourceVm, targetVm, javaEncoding, xPoweredBy, displaySourceFragment, optimizeScriptlets); } private static class JSPAdd extends RestartParentResourceAddHandler { protected JSPAdd() { super(ServletContainerDefinition.PATH_ELEMENT.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.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return UndertowService.SERVLET_CONTAINER.append(parentAddress.getLastElement().getValue()); } } private static class JSPRemove extends RestartParentResourceRemoveHandler { protected JSPRemove() { super(ServletContainerDefinition.PATH_ELEMENT.getKey()); } @Override protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException { ServletContainerAdd.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return UndertowService.SERVLET_CONTAINER.append(parentAddress.getLastElement().getValue()); } } }
15,776
54.164336
154
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/FilterLocation.java
/* * 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); }
1,233
34.257143
70
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/BufferCacheDefinition.java
/* * 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.PathElement; 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.SimpleResourceDefinition; import org.jboss.as.controller.operations.validation.IntRangeValidator; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ public class BufferCacheDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.BUFFER_CACHE); 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 List<AttributeDefinition> ATTRIBUTES = Collections.unmodifiableList(Arrays.asList(BUFFER_SIZE, BUFFERS_PER_REGION, MAX_REGIONS)); BufferCacheDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey())) .setAddHandler(BufferCacheAdd.INSTANCE) .setRemoveHandler(new ServiceRemoveStepHandler(BufferCacheService.SERVICE_NAME, BufferCacheAdd.INSTANCE)) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } }
3,746
44.144578
155
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/LocationDefinition.java
/* * 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.List; 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.ServiceRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.DynamicNameMappers; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.operations.validation.StringLengthValidator; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.undertow.filters.FilterRefDefinition; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ class LocationDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.LOCATION); static final RuntimeCapability<Void> LOCATION_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_LOCATION, true, LocationService.class) .addRequirements(Capabilities.CAPABILITY_UNDERTOW) .setDynamicNameMapper(DynamicNameMappers.GRAND_PARENT) .build(); static final AttributeDefinition HANDLER = new SimpleAttributeDefinitionBuilder(Constants.HANDLER, ModelType.STRING) .setRequired(true) .setValidator(new StringLengthValidator(1)) .setCapabilityReference(Capabilities.CAPABILITY_HANDLER) .setRestartAllServices() .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of(HANDLER); LocationDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(Constants.HOST, PATH_ELEMENT.getKey())) .setAddHandler(LocationAdd.INSTANCE) .setRemoveHandler( new ServiceRemoveStepHandler(LocationAdd.INSTANCE) { @Override protected ServiceName serviceName(String name, PathAddress address) { return LOCATION_CAPABILITY.getCapabilityServiceName(address); } }) .addCapabilities(LOCATION_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } @Override public List<? extends PersistentResourceDefinition> getChildren() { return List.of(new FilterRefDefinition()); } }
3,694
42.988095
154
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowExtensionTransformerRegistration.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, 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.EnumSet; import java.util.Set; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.transform.ExtensionTransformerRegistration; import org.jboss.as.controller.transform.SubsystemTransformerRegistration; import org.jboss.as.controller.transform.description.AttributeConverter; import org.jboss.as.controller.transform.description.DiscardAttributeChecker; import org.jboss.as.controller.transform.description.RejectAttributeChecker; import org.jboss.as.controller.transform.description.ResourceTransformationDescriptionBuilder; import org.jboss.as.controller.transform.description.TransformationDescription; import org.jboss.as.controller.transform.description.TransformationDescriptionBuilder; import org.kohsuke.MetaInfServices; /** * Registers transformers for the Undertow subsystem. * @author Paul Ferraro */ @MetaInfServices public class UndertowExtensionTransformerRegistration implements ExtensionTransformerRegistration { @Override public String getSubsystemName() { return UndertowExtension.SUBSYSTEM_NAME; } @Override public void registerTransformers(SubsystemTransformerRegistration registration) { for (UndertowSubsystemModel model : EnumSet.complementOf(EnumSet.of(UndertowSubsystemModel.CURRENT))) { ModelVersion version = model.getVersion(); ResourceTransformationDescriptionBuilder subsystem = TransformationDescriptionBuilder.Factory.createSubsystemInstance(); ResourceTransformationDescriptionBuilder server = subsystem.addChildResource(ServerDefinition.PATH_ELEMENT); for (PathElement listenerPath : Set.of(HttpListenerResourceDefinition.PATH_ELEMENT, HttpsListenerResourceDefinition.PATH_ELEMENT, AjpListenerResourceDefinition.PATH_ELEMENT)) { if (UndertowSubsystemModel.VERSION_13_0_0.requiresTransformation(version)) { server.addChildResource(listenerPath).getAttributeBuilder() .setValueConverter(AttributeConverter.DEFAULT_VALUE, ListenerResourceDefinition.WRITE_TIMEOUT, ListenerResourceDefinition.READ_TIMEOUT) .end(); } } ResourceTransformationDescriptionBuilder servletContainer = subsystem.addChildResource(ServletContainerDefinition.PATH_ELEMENT); if (UndertowSubsystemModel.VERSION_13_0_0.requiresTransformation(version)) { servletContainer.getAttributeBuilder() .setDiscard(DiscardAttributeChecker.UNDEFINED, ServletContainerDefinition.ORPHAN_SESSION_ALLOWED) .addRejectCheck(RejectAttributeChecker.DEFINED, ServletContainerDefinition.ORPHAN_SESSION_ALLOWED) .end(); servletContainer.rejectChildResource(AffinityCookieDefinition.PATH_ELEMENT); } TransformationDescription.Tools.register(subsystem.build(), registration, version); } } }
4,075
49.320988
188
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ApplicationSecurityDomainDefinition.java
/* * 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_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.PrivilegedAction; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.Set; 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.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.PathElement; 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.SimpleResourceDefinition; 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.clustering.web.container.SecurityDomainSingleSignOnManagementConfiguration; import org.wildfly.clustering.web.container.SecurityDomainSingleSignOnManagementProvider; import org.wildfly.elytron.web.undertow.server.servlet.AuthenticationManager; import org.wildfly.extension.undertow.security.jacc.JACCAuthorizationManager; import org.wildfly.extension.undertow.sso.elytron.NonDistributableSingleSignOnManagementProvider; import org.wildfly.extension.undertow.sso.elytron.SingleSignOnIdentifierFactory; 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.cache.IdentityCache; import org.wildfly.security.http.HttpExchangeSpi; import org.wildfly.security.http.HttpServerAuthenticationMechanismFactory; import org.wildfly.security.http.basic.BasicMechanismFactory; import org.wildfly.security.http.bearer.BearerMechanismFactory; import org.wildfly.security.http.cert.ClientCertMechanismFactory; import org.wildfly.security.http.digest.DigestMechanismFactory; import org.wildfly.security.http.external.ExternalMechanismFactory; import org.wildfly.security.http.form.FormMechanismFactory; import org.wildfly.security.http.spnego.SpnegoMechanismFactory; import org.wildfly.security.http.util.AggregateServerMechanismFactory; import org.wildfly.security.http.util.FilterServerMechanismFactory; import org.wildfly.security.http.util.sso.ProgrammaticSingleSignOnCache; import org.wildfly.security.http.util.sso.SingleSignOnServerMechanismFactory; import org.wildfly.security.http.util.sso.SingleSignOnConfiguration; import org.wildfly.security.http.util.sso.SingleSignOnSessionFactory; import org.wildfly.security.manager.WildFlySecurityManager; 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 <a href="mailto:[email protected]">Darran Lofthouse</a> */ public class ApplicationSecurityDomainDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.APPLICATION_SECURITY_DOMAIN); private static final Predicate<String> SERVLET_MECHANISM; static { Set<String> 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<Void> APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY = RuntimeCapability .Builder.of(CAPABILITY_APPLICATION_SECURITY_DOMAIN, true, BiFunction.class) .build(); static final SimpleAttributeDefinition HTTP_AUTHENTICATION_FACTORY = new SimpleAttributeDefinitionBuilder(Constants.HTTP_AUTHENTICATION_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(ModelNode.FALSE) .setRestartAllServices() .setRequires(Constants.HTTP_AUTHENTICATION_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_AUTHENTICATION_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(ModelNode.FALSE) .setMinSize(1) .setRestartAllServices() .build(); static final SimpleAttributeDefinition ENABLE_JASPI = new SimpleAttributeDefinitionBuilder(Constants.ENABLE_JASPI, ModelType.BOOLEAN, true) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .setRestartAllServices() .build(); static final SimpleAttributeDefinition INTEGRATED_JASPI = new SimpleAttributeDefinitionBuilder(Constants.INTEGRATED_JASPI, ModelType.BOOLEAN, true) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .setRestartAllServices() .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of(SECURITY_DOMAIN, HTTP_AUTHENTICATION_FACTORY, OVERRIDE_DEPLOYMENT_CONFIG, ENABLE_JACC, ENABLE_JASPI, INTEGRATED_JASPI); private static final AttachmentKey<KnownDeploymentsApi> KNOWN_DEPLOYMENTS_KEY = AttachmentKey.create(KnownDeploymentsApi.class); private final Set<String> knownApplicationSecurityDomains; ApplicationSecurityDomainDefinition(Set<String> knownApplicationSecurityDomains) { this(knownApplicationSecurityDomains, new AddHandler(knownApplicationSecurityDomains)); } private ApplicationSecurityDomainDefinition(Set<String> knownApplicationSecurityDomains, AbstractAddStepHandler addHandler) { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey())) .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))) .setAddHandler(addHandler) .setRemoveHandler(new RemoveHandler(knownApplicationSecurityDomains, addHandler)) ); this.knownApplicationSecurityDomains = knownApplicationSecurityDomains; } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { 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 final Set<String> knownApplicationSecurityDomains; private final SecurityDomainSingleSignOnManagementProvider provider; private AddHandler(Set<String> knownApplicationSecurityDomains) { super(ATTRIBUTES); this.knownApplicationSecurityDomains = knownApplicationSecurityDomains; Iterator<SecurityDomainSingleSignOnManagementProvider> providers = ServiceLoader.load(SecurityDomainSingleSignOnManagementProvider.class, SecurityDomainSingleSignOnManagementProvider.class.getClassLoader()).iterator(); this.provider = providers.hasNext() ? providers.next() : NonDistributableSingleSignOnManagementProvider.INSTANCE; } /* (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); this.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(); boolean enableJaspi = ENABLE_JASPI.resolveModelAttribute(context, model).asBoolean(); boolean integratedJaspi = INTEGRATED_JASPI.resolveModelAttribute(context, model).asBoolean(); String securityDomainName = context.getCurrentAddressValue(); ServiceName applicationSecurityDomainName = APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY.getCapabilityServiceName(context.getCurrentAddress()); ServiceName securityDomainServiceName = applicationSecurityDomainName.append(Constants.SECURITY_DOMAIN); ServiceBuilder<?> serviceBuilder = target .addService(applicationSecurityDomainName) .setInitialMode(Mode.LAZY); final Supplier<HttpAuthenticationFactory> httpAuthenticationFactorySupplier; final Supplier<SecurityDomain> securityDomainSupplier; if (httpServerMechanismFactory != null) { httpAuthenticationFactorySupplier = serviceBuilder.requires(context.getCapabilityServiceName(REF_HTTP_AUTHENTICATION_FACTORY, HttpAuthenticationFactory.class, httpServerMechanismFactory)); securityDomainSupplier = null; } else { securityDomainSupplier = serviceBuilder.requires(context.getCapabilityServiceName(REF_SECURITY_DOMAIN, SecurityDomain.class, securityDomain)); httpAuthenticationFactorySupplier = null; } final Supplier<UnaryOperator<HttpServerAuthenticationMechanismFactory>> transformerSupplier; final BiFunction<HttpExchangeSpi, String, IdentityCache> identityCacheSupplier; if (resource.hasChild(SingleSignOnDefinition.PATH_ELEMENT)) { ModelNode ssoModel = resource.getChild(SingleSignOnDefinition.PATH_ELEMENT).getModel(); String cookieName = SingleSignOnDefinition.Attribute.COOKIE_NAME.resolveModelAttribute(context, ssoModel).asString(); String domain = null; if (SingleSignOnDefinition.Attribute.DOMAIN.resolveModelAttribute(context, ssoModel).isDefined()) { 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(); Supplier<String> generator = new SingleSignOnIdentifierFactory(); SecurityDomainSingleSignOnManagementConfiguration configuration = new SecurityDomainSingleSignOnManagementConfiguration() { @Override public String getSecurityDomainName() { return securityDomainName; } @Override public Supplier<String> getIdentifierGenerator() { return generator; } }; this.provider.getServiceConfigurator(managerServiceName, configuration).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<SingleSignOnSessionFactory> singleSignOnSessionFactorySupplier = serviceBuilder.requires(factoryConfigurator.getServiceName()); UnaryOperator<HttpServerAuthenticationMechanismFactory> transformer = (factory) -> new SingleSignOnServerMechanismFactory(factory, singleSignOnSessionFactorySupplier.get(), singleSignOnConfiguration); identityCacheSupplier = (HttpExchangeSpi httpExchangeSpi, String mechanismName) -> ProgrammaticSingleSignOnCache.newInstance(httpExchangeSpi, mechanismName, singleSignOnSessionFactorySupplier.get(), singleSignOnConfiguration); transformerSupplier = () -> transformer; } else { identityCacheSupplier = null; transformerSupplier = () -> null; } Consumer<BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration>> deploymentConsumer = serviceBuilder.provides(applicationSecurityDomainName); Consumer<SecurityDomain> securityDomainConsumer = serviceBuilder.provides(securityDomainServiceName); ApplicationSecurityDomainService service = new ApplicationSecurityDomainService(overrideDeploymentConfig, enableJacc, enableJaspi, integratedJaspi, httpAuthenticationFactorySupplier, securityDomainSupplier, transformerSupplier, identityCacheSupplier, deploymentConsumer, securityDomainConsumer); serviceBuilder.setInstance(service); serviceBuilder.install(); KnownDeploymentsApi knownDeploymentsApi = context.getAttachment(KNOWN_DEPLOYMENTS_KEY); knownDeploymentsApi.setApplicationSecurityDomainService(service); } } private static HttpAuthenticationFactory toHttpAuthenticationFactory(final SecurityDomain securityDomain, final String realmName) { final HttpServerAuthenticationMechanismFactory mechanismFactory = new FilterServerMechanismFactory( new AggregateServerMechanismFactory(new BasicMechanismFactory(), new BearerMechanismFactory(), new ClientCertMechanismFactory(), new DigestMechanismFactory(), new ExternalMechanismFactory(), new FormMechanismFactory(), new SpnegoMechanismFactory()), SERVLET_MECHANISM); return HttpAuthenticationFactory.builder().setFactory(mechanismFactory) .setSecurityDomain(securityDomain) .setMechanismConfigurationSelector( MechanismConfigurationSelector.constantSelector(realmName == null ? MechanismConfiguration.EMPTY : MechanismConfiguration.builder() .addMechanismRealm( MechanismRealmConfiguration.builder().setRealmName(realmName).build()) .build())) .build(); } private static class RemoveHandler extends ServiceRemoveStepHandler { private final Set<String> knownApplicationSecurityDomains; /** * @param knownApplicationSecurityDomains set from which the name of the application security domain should be removed. * @param addOperation the add operation handler to use to rollback service removal. Cannot be @{code null} */ protected RemoveHandler(Set<String> knownApplicationSecurityDomains, AbstractAddStepHandler addOperation) { super(addOperation); this.knownApplicationSecurityDomains = knownApplicationSecurityDomains; } @Override protected void performRemove(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { super.performRemove(context, operation, model); this.knownApplicationSecurityDomains.remove(context.getCurrentAddressValue()); } @Override protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { super.recordCapabilitiesAndRequirements(context, operation, resource); context.deregisterCapability( RuntimeCapability.buildDynamicCapabilityName(CAPABILITY_APPLICATION_SECURITY_DOMAIN_KNOWN_DEPLOYMENTS, 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<AttributeDefinition> getAttributes() { return ATTRIBUTES; } Predicate<String> getKnownSecurityDomainPredicate() { return knownApplicationSecurityDomains::contains; } private static class ApplicationSecurityDomainService implements Service, BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration> { private final Supplier<HttpAuthenticationFactory> httpAuthenticationFactorySupplier; private final Supplier<SecurityDomain> securityDomainSupplier; private final Supplier<UnaryOperator<HttpServerAuthenticationMechanismFactory>> singleSignOnTransformerSupplier; private final BiFunction<HttpExchangeSpi, String, IdentityCache> identityCacheSupplier; private final Consumer<BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration>> deploymentConsumer; private final Consumer<SecurityDomain> securityDomainConsumer; private final boolean overrideDeploymentConfig; private final Set<RegistrationImpl> registrations = new HashSet<>(); private final boolean enableJacc; private final boolean enableJaspi; private final boolean integratedJaspi; private volatile HttpAuthenticationFactory httpAuthenticationFactory; private volatile SecurityDomain securityDomain; private ApplicationSecurityDomainService(final boolean overrideDeploymentConfig, boolean enableJacc, boolean enableJaspi, boolean integratedJaspi, final Supplier<HttpAuthenticationFactory> httpAuthenticationFactorySupplier, final Supplier<SecurityDomain> securityDomainSupplier, Supplier<UnaryOperator<HttpServerAuthenticationMechanismFactory>> singleSignOnTransformerSupplier, BiFunction<HttpExchangeSpi, String, IdentityCache> identityCacheSupplier, Consumer<BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration>> deploymentConsumer, Consumer<SecurityDomain> securityDomainConsumer) { this.overrideDeploymentConfig = overrideDeploymentConfig; this.enableJacc = enableJacc; this.enableJaspi = enableJaspi; this.integratedJaspi = integratedJaspi; this.httpAuthenticationFactorySupplier = httpAuthenticationFactorySupplier; this.securityDomainSupplier = securityDomainSupplier; this.singleSignOnTransformerSupplier = singleSignOnTransformerSupplier; this.identityCacheSupplier = identityCacheSupplier; this.deploymentConsumer = deploymentConsumer; this.securityDomainConsumer = securityDomainConsumer; } @Override public void start(StartContext context) throws StartException { deploymentConsumer.accept(this); if (httpAuthenticationFactorySupplier != null) { httpAuthenticationFactory = httpAuthenticationFactorySupplier.get(); securityDomain = httpAuthenticationFactory.getSecurityDomain(); } else { securityDomain = securityDomainSupplier.get(); } securityDomainConsumer.accept(securityDomain); } @Override public void stop(StopContext context) {} @Override public Registration apply(DeploymentInfo deploymentInfo, Function<String, RunAsIdentityMetaData> runAsMapper) { HttpAuthenticationFactory httpAuthenticationFactory = this.httpAuthenticationFactory != null ? this.httpAuthenticationFactory : toHttpAuthenticationFactory(securityDomain, getRealmName(deploymentInfo)); AuthenticationManager.Builder builder = AuthenticationManager.builder() .setHttpAuthenticationFactory(httpAuthenticationFactory) .setOverrideDeploymentConfig(overrideDeploymentConfig) .setHttpAuthenticationFactoryTransformer(singleSignOnTransformerSupplier.get()) .setIdentityCacheSupplier(identityCacheSupplier) .setRunAsMapper(runAsMapper) .setEnableJaspi(enableJaspi) .setIntegratedJaspi(integratedJaspi); 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<String> getDeployments() { synchronized (registrations) { List<String> 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<Void>) () -> { 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<String> getKnownDeployments() { return service != null ? service.getDeployments() : Collections.emptyList(); } void setApplicationSecurityDomainService(final ApplicationSecurityDomainService service) { this.service = service; } } }
31,514
53.904181
242
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowEventListener.java
/* * 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.Deployment; /** * Server/deployment lifecycle event listener. * <p/> * TODO: implement commented out Undertow events * * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author Radoslav Husar */ public interface UndertowEventListener { default void onShutdown() { } //void onDeploymentAdd(DeploymentInfo deploymentInfo, Host host); default void onDeploymentStart(Deployment deployment, Host host) { } default void onDeploymentStop(Deployment deployment, Host host) { } default void onDeploymentStart(String contextPath, Host host) { } default void onDeploymentStop(String contextPath, Host host) { } //void onDeploymentRemove(DeploymentInfo deploymentInfo, Host host); //void onHostAdd(Host host); //void onHostRemove(Host host); default void onHostStart(Host host) { } default void onHostStop(Host host) { } //void onServerAdd(Server server); //void onServerRemove(Server server); default void onServerStart(Server server) { } default void onServerStop(Server server) { } }
2,231
27.987013
88
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/EventInvoker.java
/* * 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); }
1,298
37.205882
98
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/DeploymentDefinition.java
/* * 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.client.helpers.MeasurementUnit.SECONDS; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.OP; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.SUBSYSTEM; import static org.jboss.as.controller.registry.AttributeAccess.Flag.COUNTER_METRIC; 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 io.undertow.server.session.Session; import io.undertow.server.session.SessionManager; import io.undertow.server.session.SessionManagerStatistics; import io.undertow.servlet.api.Deployment; 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; /** * @author Tomaz Cerar */ public class DeploymentDefinition extends SimpleResourceDefinition { private static final ResourceDescriptionResolver DEFAULT_RESOLVER = UndertowExtension.getResolver("deployment"); 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(); DeploymentDefinition() { super(new Parameters(PathElement.pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME), DEFAULT_RESOLVER) .setFeature(false).setRuntime()); } @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<String> 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<String> sessions = session.getAttributeNames(); for (String s : sessions) { result.add(s); } break; } case Constants.LIST_SESSION_ATTRIBUTES: { result.setEmptyList(); Set<String> 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(); } 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(ModelNode.ZERO).setStorageRuntime().build()), EXPIRED_SESSIONS(new SimpleAttributeDefinitionBuilder("expired-sessions", ModelType.INT) .setUndefinedMetricValue(ModelNode.ZERO) .setFlags(COUNTER_METRIC) .setStorageRuntime() .build()), SESSIONS_CREATED(new SimpleAttributeDefinitionBuilder("sessions-created", ModelType.INT) .setUndefinedMetricValue(ModelNode.ZERO) .setFlags(COUNTER_METRIC) .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(ModelNode.ZERO) .setMeasurementUnit(SECONDS) .setStorageRuntime() .build()), SESSION_MAX_ALIVE_TIME(new SimpleAttributeDefinitionBuilder("session-max-alive-time", ModelType.INT) .setUndefinedMetricValue(ModelNode.ZERO) .setMeasurementUnit(SECONDS) .setStorageRuntime() .build()), REJECTED_SESSIONS(new SimpleAttributeDefinitionBuilder("rejected-sessions", ModelType.INT) .setUndefinedMetricValue(ModelNode.ZERO) .setStorageRuntime() .setFlags(COUNTER_METRIC) .build()), MAX_ACTIVE_SESSIONS(new SimpleAttributeDefinitionBuilder("max-active-sessions", ModelType.INT) .setUndefinedMetricValue(ModelNode.ZERO).setStorageRuntime().build()), HIGHEST_SESSION_COUNT(new SimpleAttributeDefinitionBuilder("highest-session-count", ModelType.INT) .setUndefinedMetricValue(ModelNode.ZERO).setStorageRuntime().build()); private static final Map<String, SessionStat> 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); } } }
21,960
47.265934
180
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ListenerResourceDefinition.java
/* * 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.NAME; import static org.jboss.as.controller.registry.AttributeAccess.Flag.COUNTER_METRIC; import static org.wildfly.extension.undertow.Capabilities.REF_IO_WORKER; import static org.wildfly.extension.undertow.Capabilities.REF_SOCKET_BINDING; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; import io.undertow.UndertowOptions; import io.undertow.server.ConnectorStatistics; import io.undertow.server.handlers.ChannelUpgradeHandler; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AbstractWriteAttributeHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ModelVersion; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.ServiceRemoveStepHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.StringListAttributeDefinition; 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.client.helpers.MeasurementUnit; import org.jboss.as.controller.operations.validation.IntRangeValidator; import org.jboss.as.controller.operations.validation.LongRangeValidator; 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.controller.registry.OperationEntry; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.msc.service.ServiceController; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.io.OptionAttributeDefinition; import org.xnio.Options; /** * @author Tomaz Cerar * @author Stuart Douglas */ abstract class ListenerResourceDefinition extends PersistentResourceDefinition { static final RuntimeCapability<Void> LISTENER_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_LISTENER, true, UndertowListener.class) //.addDynamicRequirements(Capabilities.CAPABILITY_SERVER) -- has no function so don't use it .setAllowMultipleRegistrations(true) //hack to support mod_cluster's legacy profiles .build(); // only used by the subclasses Http(s)ListenerResourceDefinition static final RuntimeCapability<Void> HTTP_UPGRADE_REGISTRY_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_HTTP_UPGRADE_REGISTRY, true, ChannelUpgradeHandler.class) .setAllowMultipleRegistrations(true) .build(); static final SimpleAttributeDefinition SOCKET_BINDING = new SimpleAttributeDefinitionBuilder(Constants.SOCKET_BINDING, ModelType.STRING) .setRequired(true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1)) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF) .setCapabilityReference(REF_SOCKET_BINDING, LISTENER_CAPABILITY) .build(); static final SimpleAttributeDefinition WORKER = new SimpleAttributeDefinitionBuilder(Constants.WORKER, ModelType.STRING) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1)) .setDefaultValue(new ModelNode("default")) .setCapabilityReference(REF_IO_WORKER, LISTENER_CAPABILITY) .build(); static final SimpleAttributeDefinition BUFFER_POOL = new SimpleAttributeDefinitionBuilder(Constants.BUFFER_POOL, ModelType.STRING) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setValidator(new StringLengthValidator(1)) .setDefaultValue(new ModelNode("default")) .setCapabilityReference(Capabilities.CAPABILITY_BYTE_BUFFER_POOL, LISTENER_CAPABILITY) .build(); static final SimpleAttributeDefinition ENABLED = new SimpleAttributeDefinitionBuilder(Constants.ENABLED, ModelType.BOOLEAN) .setRequired(false) .setDeprecated(ModelVersion.create(3, 2)) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); static final SimpleAttributeDefinition REDIRECT_SOCKET = new SimpleAttributeDefinitionBuilder(Constants.REDIRECT_SOCKET, ModelType.STRING) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) .setAllowExpression(false) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SOCKET_BINDING_REF) .setCapabilityReference(REF_SOCKET_BINDING, LISTENER_CAPABILITY) .build(); static final SimpleAttributeDefinition RESOLVE_PEER_ADDRESS = new SimpleAttributeDefinitionBuilder(Constants.RESOLVE_PEER_ADDRESS, ModelType.BOOLEAN) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); static final StringListAttributeDefinition DISALLOWED_METHODS = new StringListAttributeDefinition.Builder(Constants.DISALLOWED_METHODS) .setDefaultValue(new ModelNode().add("TRACE")) .setRequired(false) .setValidator(new StringLengthValidator(0)) .setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) .setAllowExpression(true) .build(); static final SimpleAttributeDefinition SECURE = new SimpleAttributeDefinitionBuilder(Constants.SECURE, ModelType.BOOLEAN) .setDefaultValue(ModelNode.FALSE) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) .setAllowExpression(true) .build(); static final OptionAttributeDefinition BACKLOG = OptionAttributeDefinition.builder("tcp-backlog", Options.BACKLOG).setDefaultValue(new ModelNode(10000)).setAllowExpression(true).setValidator(new IntRangeValidator(1)).build(); static final OptionAttributeDefinition RECEIVE_BUFFER = OptionAttributeDefinition.builder("receive-buffer", Options.RECEIVE_BUFFER).setAllowExpression(true).setValidator(new IntRangeValidator(1)).build(); static final OptionAttributeDefinition SEND_BUFFER = OptionAttributeDefinition.builder("send-buffer", Options.SEND_BUFFER).setAllowExpression(true).setValidator(new IntRangeValidator(1)).build(); static final OptionAttributeDefinition KEEP_ALIVE = OptionAttributeDefinition.builder("tcp-keep-alive", Options.KEEP_ALIVE).setAllowExpression(true).build(); static final OptionAttributeDefinition READ_TIMEOUT = OptionAttributeDefinition.builder("read-timeout", Options.READ_TIMEOUT).setDefaultValue(new ModelNode(90000)).setAllowExpression(true).setMeasurementUnit(MeasurementUnit.MILLISECONDS).build(); static final OptionAttributeDefinition WRITE_TIMEOUT = OptionAttributeDefinition.builder("write-timeout", Options.WRITE_TIMEOUT).setDefaultValue(new ModelNode(90000)).setAllowExpression(true).setMeasurementUnit(MeasurementUnit.MILLISECONDS).build(); static final OptionAttributeDefinition MAX_CONNECTIONS = OptionAttributeDefinition.builder(Constants.MAX_CONNECTIONS, Options.CONNECTION_HIGH_WATER).setValidator(new IntRangeValidator(1)).setAllowExpression(true).build(); static final OptionAttributeDefinition MAX_HEADER_SIZE = OptionAttributeDefinition.builder("max-header-size", UndertowOptions.MAX_HEADER_SIZE).setDefaultValue(new ModelNode(UndertowOptions.DEFAULT_MAX_HEADER_SIZE)).setAllowExpression(true).setMeasurementUnit(MeasurementUnit.BYTES).setValidator(new IntRangeValidator(1)).build(); static final OptionAttributeDefinition MAX_ENTITY_SIZE = OptionAttributeDefinition.builder(Constants.MAX_POST_SIZE, UndertowOptions.MAX_ENTITY_SIZE).setDefaultValue(new ModelNode(10485760L)).setValidator(new LongRangeValidator(0)).setMeasurementUnit(MeasurementUnit.BYTES).setAllowExpression(true).build(); static final OptionAttributeDefinition BUFFER_PIPELINED_DATA = OptionAttributeDefinition.builder("buffer-pipelined-data", UndertowOptions.BUFFER_PIPELINED_DATA).setDefaultValue(ModelNode.FALSE).setAllowExpression(true).build(); static final OptionAttributeDefinition MAX_PARAMETERS = OptionAttributeDefinition.builder("max-parameters", UndertowOptions.MAX_PARAMETERS).setDefaultValue(new ModelNode(1000)).setValidator(new IntRangeValidator(1)).setAllowExpression(true).build(); static final OptionAttributeDefinition MAX_HEADERS = OptionAttributeDefinition.builder("max-headers", UndertowOptions.MAX_HEADERS).setDefaultValue(new ModelNode(200)).setValidator(new IntRangeValidator(1)).setAllowExpression(true).build(); static final OptionAttributeDefinition MAX_COOKIES = OptionAttributeDefinition.builder("max-cookies", UndertowOptions.MAX_COOKIES).setDefaultValue(new ModelNode(200)).setValidator(new IntRangeValidator(1)).setAllowExpression(true).build(); static final OptionAttributeDefinition ALLOW_ENCODED_SLASH = OptionAttributeDefinition.builder("allow-encoded-slash", UndertowOptions.ALLOW_ENCODED_SLASH).setDefaultValue(ModelNode.FALSE).setAllowExpression(true).build(); static final OptionAttributeDefinition DECODE_URL = OptionAttributeDefinition.builder("decode-url", UndertowOptions.DECODE_URL).setDefaultValue(ModelNode.TRUE).setAllowExpression(true).build(); static final OptionAttributeDefinition URL_CHARSET = OptionAttributeDefinition.builder("url-charset", UndertowOptions.URL_CHARSET).setDefaultValue(new ModelNode("UTF-8")).setAllowExpression(true).build(); static final OptionAttributeDefinition ALWAYS_SET_KEEP_ALIVE = OptionAttributeDefinition.builder("always-set-keep-alive", UndertowOptions.ALWAYS_SET_KEEP_ALIVE).setDefaultValue(ModelNode.TRUE).setAllowExpression(true).build(); static final OptionAttributeDefinition MAX_BUFFERED_REQUEST_SIZE = OptionAttributeDefinition.builder(Constants.MAX_BUFFERED_REQUEST_SIZE, UndertowOptions.MAX_BUFFERED_REQUEST_SIZE).setDefaultValue(new ModelNode(16384)).setValidator(new IntRangeValidator(1)).setMeasurementUnit(MeasurementUnit.BYTES).setAllowExpression(true).build(); static final OptionAttributeDefinition RECORD_REQUEST_START_TIME = OptionAttributeDefinition.builder("record-request-start-time", UndertowOptions.RECORD_REQUEST_START_TIME).setDefaultValue(ModelNode.FALSE).setAllowExpression(true).build(); static final OptionAttributeDefinition ALLOW_EQUALS_IN_COOKIE_VALUE = OptionAttributeDefinition.builder("allow-equals-in-cookie-value", UndertowOptions.ALLOW_EQUALS_IN_COOKIE_VALUE).setDefaultValue(ModelNode.FALSE).setAllowExpression(true).build(); static final OptionAttributeDefinition NO_REQUEST_TIMEOUT = OptionAttributeDefinition.builder("no-request-timeout", UndertowOptions.NO_REQUEST_TIMEOUT).setDefaultValue(new ModelNode(60000)).setMeasurementUnit(MeasurementUnit.MILLISECONDS).setRequired(false).setAllowExpression(true).build(); static final OptionAttributeDefinition REQUEST_PARSE_TIMEOUT = OptionAttributeDefinition.builder("request-parse-timeout", UndertowOptions.REQUEST_PARSE_TIMEOUT).setMeasurementUnit(MeasurementUnit.MILLISECONDS).setRequired(false).setAllowExpression(true).build(); static final OptionAttributeDefinition RFC6265_COOKIE_VALIDATION = OptionAttributeDefinition.builder("rfc6265-cookie-validation", UndertowOptions.ENABLE_RFC6265_COOKIE_VALIDATION).setDefaultValue(ModelNode.FALSE).setRequired(false).setAllowExpression(true).build(); static final OptionAttributeDefinition ALLOW_UNESCAPED_CHARACTERS_IN_URL = OptionAttributeDefinition.builder("allow-unescaped-characters-in-url", UndertowOptions.ALLOW_UNESCAPED_CHARACTERS_IN_URL).setDefaultValue(ModelNode.FALSE).setRequired(false).setAllowExpression(true).build(); public enum ConnectorStat { REQUEST_COUNT(new SimpleAttributeDefinitionBuilder("request-count", ModelType.LONG) .setUndefinedMetricValue(ModelNode.ZERO) .setFlags(COUNTER_METRIC) .setStorageRuntime() .build()), BYTES_SENT(new SimpleAttributeDefinitionBuilder("bytes-sent", ModelType.LONG) .setUndefinedMetricValue(ModelNode.ZERO) .setMeasurementUnit(MeasurementUnit.BYTES) .setFlags(COUNTER_METRIC) .setStorageRuntime() .build()), BYTES_RECEIVED(new SimpleAttributeDefinitionBuilder("bytes-received", ModelType.LONG) .setUndefinedMetricValue(ModelNode.ZERO) .setMeasurementUnit(MeasurementUnit.BYTES) .setFlags(COUNTER_METRIC) .setStorageRuntime() .build()), ERROR_COUNT(new SimpleAttributeDefinitionBuilder("error-count", ModelType.LONG) .setUndefinedMetricValue(ModelNode.ZERO) .setFlags(COUNTER_METRIC) .setStorageRuntime().build()), PROCESSING_TIME(new SimpleAttributeDefinitionBuilder("processing-time", ModelType.LONG) .setUndefinedMetricValue(ModelNode.ZERO) .setMeasurementUnit(MeasurementUnit.NANOSECONDS) .setFlags(COUNTER_METRIC) .setStorageRuntime() .build()), MAX_PROCESSING_TIME(new SimpleAttributeDefinitionBuilder("max-processing-time", ModelType.LONG) .setMeasurementUnit(MeasurementUnit.NANOSECONDS) .setUndefinedMetricValue(ModelNode.ZERO).setStorageRuntime().build()); private static final Map<String, ConnectorStat> MAP = new HashMap<>(); static { for (ConnectorStat stat : EnumSet.allOf(ConnectorStat.class)) { MAP.put(stat.toString(), stat); } } final AttributeDefinition definition; private ConnectorStat(final AttributeDefinition definition) { this.definition = definition; } @Override public final String toString() { return definition.getName(); } public static synchronized ConnectorStat getStat(final String stringForm) { return MAP.get(stringForm); } } static final Collection<OptionAttributeDefinition> LISTENER_OPTIONS = List.of(MAX_HEADER_SIZE, MAX_ENTITY_SIZE, BUFFER_PIPELINED_DATA, MAX_PARAMETERS, MAX_HEADERS, MAX_COOKIES, ALLOW_ENCODED_SLASH, DECODE_URL, URL_CHARSET, ALWAYS_SET_KEEP_ALIVE, MAX_BUFFERED_REQUEST_SIZE, RECORD_REQUEST_START_TIME, ALLOW_EQUALS_IN_COOKIE_VALUE, NO_REQUEST_TIMEOUT, REQUEST_PARSE_TIMEOUT, RFC6265_COOKIE_VALIDATION, ALLOW_UNESCAPED_CHARACTERS_IN_URL); static final Collection<OptionAttributeDefinition> SOCKET_OPTIONS = List.of(BACKLOG, RECEIVE_BUFFER, SEND_BUFFER, KEEP_ALIVE, READ_TIMEOUT, WRITE_TIMEOUT, MAX_CONNECTIONS); private static final Collection<AttributeDefinition> SIMPLE_ATTRIBUTES = List.of(SOCKET_BINDING, WORKER, BUFFER_POOL, ENABLED, RESOLVE_PEER_ADDRESS, DISALLOWED_METHODS, SECURE); static final Collection<AttributeDefinition> ATTRIBUTES = collectAttributes(); private static Collection<AttributeDefinition> collectAttributes() { Collection<AttributeDefinition> attributes = new ArrayList<>(SIMPLE_ATTRIBUTES.size() + LISTENER_OPTIONS.size() + SOCKET_OPTIONS.size()); attributes.addAll(SIMPLE_ATTRIBUTES); attributes.addAll(LISTENER_OPTIONS); attributes.addAll(SOCKET_OPTIONS); return Collections.unmodifiableCollection(attributes); } private final Function<Collection<AttributeDefinition>, AbstractAddStepHandler> addHandlerFactory; private final Map<AttributeDefinition, OperationStepHandler> writeAttributeHandlers; public ListenerResourceDefinition(SimpleResourceDefinition.Parameters parameters, Function<Collection<AttributeDefinition>, AbstractAddStepHandler> addHandlerFactory, Map<AttributeDefinition, OperationStepHandler> writeAttributeHandlers) { // this Persistent Parameters will be cast to Parameters super(parameters.setDescriptionResolver(UndertowExtension.getResolver(Constants.LISTENER)).addCapabilities(LISTENER_CAPABILITY)); this.addHandlerFactory = addHandlerFactory; this.writeAttributeHandlers = new HashMap<>(); this.writeAttributeHandlers.putAll(writeAttributeHandlers); this.writeAttributeHandlers.put(ENABLED, new EnabledAttributeHandler()); } @Override public void registerOperations(ManagementResourceRegistration resourceRegistration) { AbstractAddStepHandler addHandler = this.addHandlerFactory.apply(this.getAttributes()); super.registerAddOperation(resourceRegistration, addHandler, OperationEntry.Flag.RESTART_NONE); super.registerRemoveOperation(resourceRegistration, new ServiceRemoveStepHandler(addHandler), OperationEntry.Flag.RESTART_NONE); resourceRegistration.registerOperationHandler(ResetConnectorStatisticsHandler.DEFINITION, ResetConnectorStatisticsHandler.INSTANCE); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { Collection<AttributeDefinition> attributes = this.getAttributes(); OperationStepHandler defaultWriteAttributeHandler = new ReloadRequiredWriteAttributeHandler(attributes); for (AttributeDefinition attribute : attributes) { OperationStepHandler writeAttributeHandler = this.writeAttributeHandlers.getOrDefault(attribute, defaultWriteAttributeHandler); resourceRegistration.registerReadWriteAttribute(attribute, null, writeAttributeHandler); } for(ConnectorStat attr : ConnectorStat.values()) { resourceRegistration.registerMetric(attr.definition, ReadStatisticHandler.INSTANCE); } } @Override public List<AccessConstraintDefinition> getAccessConstraints() { return List.of(new SensitiveTargetAccessConstraintDefinition(new SensitivityClassification(UndertowExtension.SUBSYSTEM_NAME, "web-connector", false, false, false))); } private static class ReadStatisticHandler implements OperationStepHandler { public static final ReadStatisticHandler INSTANCE = new ReadStatisticHandler(); private ReadStatisticHandler() { } public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ListenerService service = getListenerService(context); if (service == null) { return; } String op = operation.get(NAME).asString(); ConnectorStatistics stats = service.getOpenListener().getConnectorStatistics(); if(stats != null) { ConnectorStat element = ConnectorStat.getStat(op); switch (element) { case BYTES_RECEIVED: context.getResult().set(stats.getBytesReceived()); break; case BYTES_SENT: context.getResult().set(stats.getBytesSent()); break; case ERROR_COUNT: context.getResult().set(stats.getErrorCount()); break; case MAX_PROCESSING_TIME: context.getResult().set(stats.getMaxProcessingTime()); break; case PROCESSING_TIME: context.getResult().set(stats.getProcessingTime()); break; case REQUEST_COUNT: context.getResult().set(stats.getRequestCount()); break; } } } } static ListenerService getListenerService(OperationContext context) { final String name = context.getCurrentAddressValue(); ServiceName serviceName = LISTENER_CAPABILITY.getCapabilityServiceName(name); ServiceController<ListenerService> listenerSC = (ServiceController<ListenerService>) context.getServiceRegistry(false).getService(serviceName); if (listenerSC == null || listenerSC.getState() != ServiceController.State.UP) { return null; } return listenerSC.getValue(); } private static class EnabledAttributeHandler extends AbstractWriteAttributeHandler<Boolean> { protected EnabledAttributeHandler() { super(ListenerResourceDefinition.ENABLED); } @Override protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Boolean> handbackHolder) throws OperationFailedException { boolean enabled = resolvedValue.asBoolean(); // We don't try and analyze currentValue to see if we were already enabled, as the resolution result // may be different now than it was before (different system props, or vault contents) // Instead we consider the previous setting to be enabled if the service Mode != Mode.NEVER ListenerService listenerService = getListenerService(context); if (listenerService != null) { boolean currentEnabled = listenerService.isEnabled(); handbackHolder.setHandback(currentEnabled); listenerService.setEnabled(enabled); } return false; } @Override protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, Boolean handback) throws OperationFailedException { if (handback != null) { ListenerService listenerService = getListenerService(context); if (listenerService != null) { listenerService.setEnabled(handback); } } } } }
23,948
62.525199
337
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HostSingleSignOnDefinition.java
/* * 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.AdminOnlyOperationStepHandlerTransformer; import org.jboss.as.clustering.controller.BinaryCapabilityNameResolver; import org.jboss.as.clustering.controller.ResourceDescriptor; import org.jboss.as.clustering.controller.SimpleResourceRegistrar; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.registry.ManagementResourceRegistration; /** * @author Paul Ferraro */ public class HostSingleSignOnDefinition extends SingleSignOnDefinition { public static final RuntimeCapability<Void> HOST_SSO_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_HOST_SSO, true) .addRequirements(Capabilities.CAPABILITY_UNDERTOW) .setDynamicNameMapper(BinaryCapabilityNameResolver.GRANDPARENT_PARENT) .build(); public HostSingleSignOnDefinition() { super(); setDeprecated(UndertowSubsystemModel.VERSION_12_0_0.getVersion()); } @Override public void registerOperations(ManagementResourceRegistration registration) { ResourceDescriptor descriptor = new ResourceDescriptor(this.getResourceDescriptionResolver()) .addAttributes(SingleSignOnDefinition.Attribute.class).addCapabilities(() -> HOST_SSO_CAPABILITY) .setAddOperationTransformation(AdminOnlyOperationStepHandlerTransformer.INSTANCE) ; new SimpleResourceRegistrar(descriptor, null).register(registration); } }
2,552
45.418182
138
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AccessLogAttribute.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.undertow; import java.util.Objects; import java.util.function.Function; import io.undertow.attribute.ExchangeAttribute; import io.undertow.server.HttpServerExchange; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class AccessLogAttribute implements Comparable<AccessLogAttribute> { private final String key; private final ExchangeAttribute exchangeAttribute; private final Function<String, Object> valueConverter; private AccessLogAttribute(final String key, final ExchangeAttribute exchangeAttribute, final Function<String, Object> valueConverter) { this.key = key; this.exchangeAttribute = exchangeAttribute; this.valueConverter = valueConverter; } /** * Creates a new attribute. * * @param key the key for the attribute * @param exchangeAttribute the exchange attribute which resolves the value * * @return the new attribute */ static AccessLogAttribute of(final String key, final ExchangeAttribute exchangeAttribute) { return new AccessLogAttribute(key, exchangeAttribute, null); } /** * Creates a new attribute. * * @param key the key for the attribute * @param exchangeAttribute the exchange attribute which resolves the value * @param valueConverter the converter used to convert the * {@linkplain ExchangeAttribute#readAttribute(HttpServerExchange) string} into a different * type * * @return the new attribute */ static AccessLogAttribute of(final String key, final ExchangeAttribute exchangeAttribute, final Function<String, Object> valueConverter) { return new AccessLogAttribute(key, exchangeAttribute, valueConverter); } /** * Returns the key used for the structured log output. * * @return the key */ String getKey() { return key; } /** * Resolves the value for the attribute. * * @param exchange the exchange to resolve the value from * * @return the value of the attribute */ Object resolveAttribute(final HttpServerExchange exchange) { if (valueConverter == null) { return exchangeAttribute.readAttribute(exchange); } return valueConverter.apply(exchangeAttribute.readAttribute(exchange)); } @Override public int compareTo(final AccessLogAttribute o) { return key.compareTo(o.key); } @Override public int hashCode() { return Objects.hash(key); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!(obj instanceof AccessLogAttribute)) { return false; } final AccessLogAttribute other = (AccessLogAttribute) obj; return key.equals(other.key); } @Override public String toString() { return getClass().getSimpleName() + "{key=" + key + ", exchangeAttribute=" + exchangeAttribute + ", valueConverter=" + valueConverter + "}"; } }
3,779
31.033898
142
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ServerDefinition.java
/* * 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.List; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathElement; 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.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.web.host.CommonWebServer; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ class ServerDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SERVER); static final RuntimeCapability<Void> SERVER_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_SERVER, true, Server.class) .addRequirements(Capabilities.CAPABILITY_UNDERTOW) .build(); static final SimpleAttributeDefinition DEFAULT_HOST = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_HOST, ModelType.STRING) .setRequired(false) .setAllowExpression(true) .setDefaultValue(new ModelNode("default-host")) .setRestartAllServices() .build(); static final SimpleAttributeDefinition SERVLET_CONTAINER = new SimpleAttributeDefinitionBuilder(Constants.SERVLET_CONTAINER, ModelType.STRING) .setRequired(false) .setDefaultValue(new ModelNode("default")) .setRestartAllServices() .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of(DEFAULT_HOST, SERVLET_CONTAINER); ServerDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey())) .setAddHandler(new ServerAdd()) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .addCapabilities(SERVER_CAPABILITY, CommonWebServer.CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } @Override protected List<? extends PersistentResourceDefinition> getChildren() { return List.of( new AjpListenerResourceDefinition(), new HttpListenerResourceDefinition(), new HttpsListenerResourceDefinition(), new HostDefinition()); } }
3,690
42.423529
146
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/CrawlerSessionManagementDefinition.java
/* * 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.ExpressionResolver; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; 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.SimpleResourceDefinition; 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.List; /** * Global session cookie config * * @author Stuart Douglas */ class CrawlerSessionManagementDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.CRAWLER_SESSION_MANAGEMENT); 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(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of(USER_AGENTS, SESSION_TIMEOUT); CrawlerSessionManagementDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKeyValuePair())) .setAddHandler(new CrawlerSessionManagementAdd()) .setRemoveHandler(new CrawlerSessionManagementRemove()) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static CrawlerSessionManagerConfig getConfig(final ExpressionResolver 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.PATH_ELEMENT.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.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return UndertowService.SERVLET_CONTAINER.append(parentAddress.getLastElement().getValue()); } } private static class CrawlerSessionManagementRemove extends RestartParentResourceRemoveHandler { protected CrawlerSessionManagementRemove() { super(ServletContainerDefinition.PATH_ELEMENT.getKey()); } @Override protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException { ServletContainerAdd.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return UndertowService.SERVLET_CONTAINER.append(parentAddress.getLastElement().getValue()); } } }
6,067
43.291971
154
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AbstractHttpListenerResourceDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, 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.List; import java.util.Map; import java.util.function.Function; import io.undertow.UndertowOptions; import io.undertow.protocols.http2.Http2Channel; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; 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; /** * Common base class for HTTP and HTTPS resource definitions. * @author Paul Ferraro */ abstract class AbstractHttpListenerResourceDefinition extends ListenerResourceDefinition { static final OptionAttributeDefinition HTTP2_ENABLE_PUSH = OptionAttributeDefinition.builder("http2-enable-push", UndertowOptions.HTTP2_SETTINGS_ENABLE_PUSH) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.TRUE) .build(); static final OptionAttributeDefinition HTTP2_HEADER_TABLE_SIZE = OptionAttributeDefinition.builder("http2-header-table-size", UndertowOptions.HTTP2_SETTINGS_HEADER_TABLE_SIZE) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.BYTES) .setDefaultValue(new ModelNode(UndertowOptions.HTTP2_SETTINGS_HEADER_TABLE_SIZE_DEFAULT)) .setValidator(new IntRangeValidator(1)) .build(); static final OptionAttributeDefinition HTTP2_INITIAL_WINDOW_SIZE = OptionAttributeDefinition.builder("http2-initial-window-size", UndertowOptions.HTTP2_SETTINGS_INITIAL_WINDOW_SIZE) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.BYTES) .setDefaultValue(new ModelNode(Http2Channel.DEFAULT_INITIAL_WINDOW_SIZE)) .setValidator(new IntRangeValidator(1)) .build(); static final OptionAttributeDefinition HTTP2_MAX_CONCURRENT_STREAMS = OptionAttributeDefinition.builder("http2-max-concurrent-streams", UndertowOptions.HTTP2_SETTINGS_MAX_CONCURRENT_STREAMS) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setValidator(new IntRangeValidator(1)) .build(); static final OptionAttributeDefinition HTTP2_MAX_HEADER_LIST_SIZE = OptionAttributeDefinition.builder("http2-max-header-list-size", UndertowOptions.HTTP2_SETTINGS_MAX_HEADER_LIST_SIZE) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.BYTES) .setValidator(new IntRangeValidator(1)) .build(); static final OptionAttributeDefinition HTTP2_MAX_FRAME_SIZE = OptionAttributeDefinition.builder("http2-max-frame-size", UndertowOptions.HTTP2_SETTINGS_MAX_FRAME_SIZE) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.BYTES) .setDefaultValue(new ModelNode(Http2Channel.DEFAULT_MAX_FRAME_SIZE)) .setValidator(new IntRangeValidator(1)) .build(); static final SimpleAttributeDefinition CERTIFICATE_FORWARDING = new SimpleAttributeDefinitionBuilder(Constants.CERTIFICATE_FORWARDING, ModelType.BOOLEAN) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); static final SimpleAttributeDefinition PROXY_ADDRESS_FORWARDING = new SimpleAttributeDefinitionBuilder("proxy-address-forwarding", ModelType.BOOLEAN) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); static final OptionAttributeDefinition REQUIRE_HOST_HTTP11 = OptionAttributeDefinition.builder("require-host-http11", UndertowOptions.REQUIRE_HOST_HTTP11) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); static final SimpleAttributeDefinition PROXY_PROTOCOL = new SimpleAttributeDefinitionBuilder(Constants.PROXY_PROTOCOL, ModelType.BOOLEAN) .setDefaultValue(ModelNode.FALSE) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_RESOURCE_SERVICES) .setAllowExpression(true) .build(); static final OptionAttributeDefinition ENABLE_HTTP2 = OptionAttributeDefinition.builder(Constants.ENABLE_HTTP2, UndertowOptions.ENABLE_HTTP2) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of( ENABLE_HTTP2, HTTP2_ENABLE_PUSH, HTTP2_HEADER_TABLE_SIZE, HTTP2_INITIAL_WINDOW_SIZE, HTTP2_MAX_CONCURRENT_STREAMS, HTTP2_MAX_HEADER_LIST_SIZE, HTTP2_MAX_FRAME_SIZE, CERTIFICATE_FORWARDING, PROXY_ADDRESS_FORWARDING, REQUIRE_HOST_HTTP11, PROXY_PROTOCOL); AbstractHttpListenerResourceDefinition(SimpleResourceDefinition.Parameters parameters, Function<Collection<AttributeDefinition>, AbstractAddStepHandler> addHandlerFactory) { super(parameters, addHandlerFactory, Map.of(WORKER, new HttpListenerWorkerAttributeWriteHandler(WORKER))); } }
7,428
47.875
194
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowSubsystemModel.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, 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.ModelVersion; import org.jboss.as.controller.SubsystemModel; /** * Enumerates the supported versions of the Undertow subsystem model. * @author Paul Ferraro */ public enum UndertowSubsystemModel implements SubsystemModel { VERSION_11_0_0(11), // WildFly 23-26.x, EAP 7.4.x VERSION_12_0_0(12), // WildFly 27 VERSION_13_0_0(13), // WildFly 28-present ; static final UndertowSubsystemModel CURRENT = VERSION_13_0_0; private final ModelVersion version; UndertowSubsystemModel(int major) { this(major, 0, 0); } UndertowSubsystemModel(int major, int minor) { this(major, minor, 0); } UndertowSubsystemModel(int major, int minor, int micro) { this.version = ModelVersion.create(major, minor, micro); } @Override public ModelVersion getVersion() { return this.version; } }
1,963
32.288136
70
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/PersistentSessionsDefinition.java
/* * 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.SessionPersistenceManager; import org.jboss.as.controller.AttributeDefinition; 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.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.SimpleResourceDefinition; import org.jboss.as.controller.services.path.PathManager; import org.jboss.as.controller.services.path.PathManagerService; import org.jboss.as.server.Services; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.modules.ModuleLoader; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; import java.util.Collection; import java.util.List; import java.util.function.Consumer; import java.util.function.Supplier; /** * Global session cookie config * * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ class PersistentSessionsDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.PERSISTENT_SESSIONS); protected static final SimpleAttributeDefinition PATH = new SimpleAttributeDefinitionBuilder(Constants.PATH, ModelType.STRING, true) .setRestartAllServices() .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition RELATIVE_TO = new SimpleAttributeDefinitionBuilder(Constants.RELATIVE_TO, ModelType.STRING, true) .setRestartAllServices() .setAllowExpression(true) .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of(PATH, RELATIVE_TO); PersistentSessionsDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKeyValuePair())) .setAddHandler(new PersistentSessionsAdd()) .setRemoveHandler(new PersistentSessionsRemove()) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } public static boolean isEnabled(final ModelNode model) throws OperationFailedException { return model.isDefined(); } private static class PersistentSessionsAdd extends RestartParentResourceAddHandler { protected PersistentSessionsAdd() { super(ServletContainerDefinition.PATH_ELEMENT.getKey()); } public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { super.execute(context, operation); if (requiresRuntime(context)) { context.addStep(new OperationStepHandler() { public void execute(final OperationContext context, final ModelNode operation) throws OperationFailedException { performRuntime(context, operation, operation); context.completeStep(new OperationContext.RollbackHandler() { @Override public void handleRollback(OperationContext context, ModelNode operation) { rollbackRuntime(context, operation, operation); } }); } }, OperationContext.Stage.RUNTIME); } } private void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { if (isEnabled(model)) { final ModelNode pathValue = PATH.resolveModelAttribute(context, model); final ServiceBuilder<?> sb = context.getServiceTarget().addService(AbstractPersistentSessionManager.SERVICE_NAME); final Consumer<SessionPersistenceManager> sConsumer = sb.provides(AbstractPersistentSessionManager.SERVICE_NAME); final Supplier<ModuleLoader> mlSupplier = sb.requires(Services.JBOSS_SERVICE_MODULE_LOADER); if (pathValue.isDefined()) { final String path = pathValue.asString(); final ModelNode relativeToValue = RELATIVE_TO.resolveModelAttribute(context, model); final String relativeTo = relativeToValue.isDefined() ? relativeToValue.asString() : null; final Supplier<PathManager> pmSupplier = sb.requires(PathManagerService.SERVICE_NAME); sb.setInstance(new DiskBasedModularPersistentSessionManager(sConsumer, mlSupplier, pmSupplier, path, relativeTo)); } else { sb.setInstance(new InMemoryModularPersistentSessionManager(sConsumer, mlSupplier)); } sb.install(); } } private void rollbackRuntime(OperationContext context, ModelNode operation, ModelNode model) { } @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.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return UndertowService.SERVLET_CONTAINER.append(parentAddress.getLastElement().getValue()); } } private static class PersistentSessionsRemove extends RestartParentResourceRemoveHandler { protected PersistentSessionsRemove() { super(ServletContainerDefinition.PATH_ELEMENT.getKey()); } @Override protected void removeServices(OperationContext context, ServiceName parentService, ModelNode parentModel) throws OperationFailedException { super.removeServices(context, parentService, parentModel); context.removeService(AbstractPersistentSessionManager.SERVICE_NAME); } @Override protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException { ServletContainerAdd.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return UndertowService.SERVLET_CONTAINER.append(parentAddress.getLastElement().getValue()); } } }
8,355
45.165746
154
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/DeploymentServletDefinition.java
/* * 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.client.helpers.MeasurementUnit.MILLISECONDS; import static org.jboss.as.controller.registry.AttributeAccess.Flag.COUNTER_METRIC; import io.undertow.server.handlers.MetricsHandler; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.ServletInfo; 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; /** * @author Tomaz Cerar * @created 23.2.12 18:35 */ public class DeploymentServletDefinition extends SimpleResourceDefinition { 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) .setUndefinedMetricValue(ModelNode.ZERO) .setMeasurementUnit(MILLISECONDS) .setStorageRuntime() .build(); static final SimpleAttributeDefinition MIN_REQUEST_TIME = new SimpleAttributeDefinitionBuilder("min-request-time", ModelType.LONG) .setUndefinedMetricValue(ModelNode.ZERO) .setMeasurementUnit(MILLISECONDS) .setStorageRuntime() .build(); static final SimpleAttributeDefinition TOTAL_REQUEST_TIME = new SimpleAttributeDefinitionBuilder("total-request-time", ModelType.LONG) .setUndefinedMetricValue(ModelNode.ZERO) .setMeasurementUnit(MILLISECONDS) .setFlags(COUNTER_METRIC) .setStorageRuntime() .build(); static final SimpleAttributeDefinition REQUEST_COUNT = new SimpleAttributeDefinitionBuilder("request-count", ModelType.LONG) .setUndefinedMetricValue(ModelNode.ZERO) .setFlags(COUNTER_METRIC) .setStorageRuntime() .build(); static final SimpleListAttributeDefinition SERVLET_MAPPINGS = new SimpleListAttributeDefinition.Builder("mappings", new SimpleAttributeDefinitionBuilder("mapping", ModelType.STRING).setRequired(false).build()) .setRequired(false) .setStorageRuntime() .build(); 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 MetricsHandler.MetricResult metricResult) { response.set((long) metricResult.getMaxRequestTime()); } }); registration.registerMetric(MIN_REQUEST_TIME, new AbstractMetricsHandler() { @Override void handle(final ModelNode response, final MetricsHandler.MetricResult metricResult) { response.set((long) metricResult.getMinRequestTime()); } }); registration.registerMetric(TOTAL_REQUEST_TIME, new AbstractMetricsHandler() { @Override void handle(final ModelNode response, final MetricsHandler.MetricResult metricResult) { response.set(metricResult.getTotalRequestTime()); } }); registration.registerMetric(REQUEST_COUNT, new AbstractMetricsHandler() { @Override void handle(final ModelNode response, final MetricsHandler.MetricResult metricResult) { response.set(metricResult.getTotalRequests()); } }); registration.registerReadOnlyAttribute(SERVLET_MAPPINGS, new OperationStepHandler() { @Override public void execute(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() - 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) { final ServiceController<?> deploymentServiceController = context.getServiceRegistry(false).getService(UndertowService.deploymentServiceName(server, host, path)); if (deploymentServiceController == null || deploymentServiceController.getState() != ServiceController.State.UP) { return; } final UndertowDeploymentService deploymentService = (UndertowDeploymentService) deploymentServiceController.getService(); final DeploymentInfo deploymentInfo = deploymentService.getDeploymentInfo(); final ServletInfo servlet = deploymentInfo.getServlets().get(context.getCurrentAddressValue()); ModelNode response = new ModelNode(); response.setEmptyList(); for (String mapping : servlet.getMappings()) { response.add(mapping); } } }, OperationContext.Stage.RUNTIME); } }); } abstract static class AbstractMetricsHandler implements OperationStepHandler { abstract void handle(ModelNode response, MetricsHandler.MetricResult metricResult); @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) { final ServiceController<?> deploymentServiceController = context.getServiceRegistry(false).getService(UndertowService.deploymentServiceName(server, host, path)); if (deploymentServiceController == null || deploymentServiceController.getState() != ServiceController.State.UP) { return; } final UndertowDeploymentService deploymentService = (UndertowDeploymentService) deploymentServiceController.getService(); final DeploymentInfo deploymentInfo = deploymentService.getDeploymentInfo(); final UndertowMetricsCollector collector = (UndertowMetricsCollector)deploymentInfo.getMetricsCollector(); MetricsHandler.MetricResult result = collector != null ? collector.getMetrics(context.getCurrentAddressValue()) : null; if (result != null) { final ModelNode response = new ModelNode(); handle(response, result); context.getResult().set(response); } } }, OperationContext.Stage.RUNTIME); } } }
10,400
54.324468
213
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpsListenerAdd.java
/* * 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_SSL_CONTEXT; import static org.wildfly.extension.undertow.logging.UndertowLogger.ROOT_LOGGER; import javax.net.ssl.SSLContext; import io.undertow.server.ListenerRegistry; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; import org.xnio.OptionMap; import java.util.Collection; import java.util.function.Consumer; import java.util.function.Supplier; /** * Add handler for HTTPS listeners. * * @author <a href="mailto:[email protected]">Darran Lofthouse</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ class HttpsListenerAdd extends ListenerAdd<HttpsListenerService> { HttpsListenerAdd(Collection<AttributeDefinition> attributes) { super(attributes); } @Override HttpsListenerService createService(final Consumer<ListenerService> serviceConsumer, final String name, final String serverName, final OperationContext context, ModelNode model, OptionMap listenerOptions, OptionMap socketOptions) throws OperationFailedException { OptionMap.Builder builder = OptionMap.builder().addAll(socketOptions); ModelNode securityRealmModel = HttpsListenerResourceDefinition.SECURITY_REALM.resolveModelAttribute(context, model); final boolean proxyProtocol = AbstractHttpListenerResourceDefinition.PROXY_PROTOCOL.resolveModelAttribute(context, model).asBoolean(); String cipherSuites = null; if(securityRealmModel.isDefined()) { throw ROOT_LOGGER.runtimeSecurityRealmUnsupported(); } OptionMap.Builder listenerBuilder = OptionMap.builder().addAll(listenerOptions); AbstractHttpListenerResourceDefinition.ENABLE_HTTP2.resolveOption(context, model, listenerBuilder); HttpListenerAdd.handleHttp2Options(context, model, listenerBuilder); AbstractHttpListenerResourceDefinition.REQUIRE_HOST_HTTP11.resolveOption(context, model,listenerBuilder); final boolean certificateForwarding = AbstractHttpListenerResourceDefinition.CERTIFICATE_FORWARDING.resolveModelAttribute(context, model).asBoolean(); final boolean proxyAddressForwarding = AbstractHttpListenerResourceDefinition.PROXY_ADDRESS_FORWARDING.resolveModelAttribute(context, model).asBoolean(); return new HttpsListenerService(serviceConsumer, context.getCurrentAddress(), serverName, listenerBuilder.getMap(), cipherSuites, builder.getMap(), certificateForwarding, proxyAddressForwarding, proxyProtocol); } @Override void configureAdditionalDependencies(OperationContext context, CapabilityServiceBuilder<?> serviceBuilder, ModelNode model, HttpsListenerService service) throws OperationFailedException { service.getHttpListenerRegistry().set(serviceBuilder.requiresCapability(Capabilities.REF_HTTP_LISTENER_REGISTRY, ListenerRegistry.class)); final ModelNode sslContextModel = HttpsListenerResourceDefinition.SSL_CONTEXT.resolveModelAttribute(context, model); final String sslContextRef = sslContextModel.isDefined() ? sslContextModel.asString() : null; final Supplier<SSLContext> sslContextInjector = sslContextRef != null ? serviceBuilder.requiresCapability(REF_SSL_CONTEXT, SSLContext.class, sslContextRef) : null; service.setSSLContextSupplier(()-> { if (sslContextRef != null) { return sslContextInjector.get(); } try { return SSLContext.getDefault(); } catch (Exception e) { throw new IllegalStateException(e); } }); } }
4,854
47.069307
266
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AjpListenerAdd.java
/* * 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.AttributeDefinition; 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; import java.util.Collection; import java.util.function.Consumer; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ class AjpListenerAdd extends ListenerAdd<AjpListenerService> { AjpListenerAdd(Collection<AttributeDefinition> attributes) { super(attributes); } @Override AjpListenerService createService(final Consumer<ListenerService> serviceConsumer, final 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(serviceConsumer, context.getCurrentAddress(), scheme, listenerBuilder.getMap(), socketOptions); } @Override void configureAdditionalDependencies(OperationContext context, CapabilityServiceBuilder<?> serviceBuilder, ModelNode model, AjpListenerService service) throws OperationFailedException { ModelNode redirectBindingRef = ListenerResourceDefinition.REDIRECT_SOCKET.resolveModelAttribute(context, model); if (redirectBindingRef.isDefined()) { service.getRedirectSocket().set(serviceBuilder.requiresCapability(REF_SOCKET_BINDING, SocketBinding.class, redirectBindingRef.asString())); } } }
3,238
46.632353
264
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/EventLoggerService.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.undertow; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executor; import java.util.function.Function; import java.util.function.Supplier; import io.undertow.predicate.Predicate; import io.undertow.predicate.Predicates; import io.undertow.server.HttpHandler; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.event.logger.EventLogger; import org.wildfly.event.logger.JsonEventFormatter; import org.wildfly.event.logger.StdoutEventWriter; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.xnio.XnioWorker; /** * A service which creates an asynchronous {@linkplain EventLogger event logger} which writes to {@code stdout} in JSON * structured format. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class EventLoggerService implements Service { private final Set<AccessLogAttribute> attributes; private final boolean includeHostName; private final Map<String, Object> metadata; private final Predicate predicate; private final Supplier<Host> host; private final Supplier<XnioWorker> worker; /** * Creates a new service. * * @param predicate the predicate that determines if the request should be logged * @param metadata a map of metadata to be prepended to the structured output * @param includeHostName {@code true} to include the host name in the structured JSON output * @param host the host service supplier * @param worker the worker service supplier for the * {@linkplain EventLogger#createAsyncLogger(String, Executor) async logger} */ EventLoggerService(final Collection<AccessLogAttribute> attributes, final Predicate predicate, final Map<String, Object> metadata, final boolean includeHostName, final Supplier<Host> host, final Supplier<XnioWorker> worker) { this.attributes = new CopyOnWriteArraySet<>(attributes); this.predicate = predicate == null ? Predicates.truePredicate() : predicate; this.metadata = metadata; this.includeHostName = includeHostName; this.host = host; this.worker = worker; } @Override @SuppressWarnings("Convert2Lambda") public void start(final StartContext context) throws StartException { final Host host = this.host.get(); // Create the JSON event formatter final JsonEventFormatter.Builder formatterBuilder = JsonEventFormatter.builder() .setIncludeTimestamp(false); if (includeHostName) { formatterBuilder.addMetaData("hostName", host.getName()); } if (metadata != null && !metadata.isEmpty()) { formatterBuilder.addMetaData(metadata); } final JsonEventFormatter formatter = formatterBuilder.build(); final EventLogger eventLogger = EventLogger.createAsyncLogger("web-access", StdoutEventWriter.of(formatter), worker.get()); UndertowLogger.ROOT_LOGGER.debugf("Adding console-access-log for host %s", host.getName()); host.setAccessLogHandler(new Function<HttpHandler, HttpHandler>() { @Override public HttpHandler apply(final HttpHandler httpHandler) { return new EventLoggerHttpHandler(httpHandler, predicate, attributes, eventLogger); } }); } @Override public void stop(final StopContext context) { final Host host = this.host.get(); UndertowLogger.ROOT_LOGGER.debugf("Removing console-access-log for host %s", host.getName()); host.setAccessLogHandler(null); } }
4,487
41.339623
134
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowPersistentResourceXMLDescriptionFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, 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.PersistentResourceXMLDescription.builder; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import org.jboss.as.clustering.controller.Attribute; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.operations.common.Util; import org.wildfly.extension.undertow.filters.CustomFilterDefinition; import org.wildfly.extension.undertow.filters.ErrorPageDefinition; import org.wildfly.extension.undertow.filters.ExpressionFilterDefinition; import org.wildfly.extension.undertow.filters.FilterDefinitions; import org.wildfly.extension.undertow.filters.FilterRefDefinition; import org.wildfly.extension.undertow.filters.GzipFilterDefinition; import org.wildfly.extension.undertow.filters.ModClusterDefinition; import org.wildfly.extension.undertow.filters.NoAffinityResourceDefinition; import org.wildfly.extension.undertow.filters.RankedAffinityResourceDefinition; import org.wildfly.extension.undertow.filters.RequestLimitHandlerDefinition; import org.wildfly.extension.undertow.filters.ResponseHeaderFilterDefinition; import org.wildfly.extension.undertow.filters.RewriteFilterDefinition; import org.wildfly.extension.undertow.filters.SingleAffinityResourceDefinition; import org.wildfly.extension.undertow.handlers.FileHandlerDefinition; import org.wildfly.extension.undertow.handlers.HandlerDefinitions; import org.wildfly.extension.undertow.handlers.ReverseProxyHandlerDefinition; import org.wildfly.extension.undertow.handlers.ReverseProxyHandlerHostDefinition; /** * Factory for creating the {@link org.jboss.as.controller.PersistentResourceXMLDescription} for a given schema. * @author Paul Ferraro */ public enum UndertowPersistentResourceXMLDescriptionFactory implements Function<UndertowSubsystemSchema, PersistentResourceXMLDescription> { INSTANCE; @Override public PersistentResourceXMLDescription apply(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(UndertowRootDefinition.PATH_ELEMENT, schema.getNamespace()); if (schema.since(UndertowSubsystemSchema.VERSION_6_0)) { builder.addChild(builder(ByteBufferPoolDefinition.PATH_ELEMENT).addAttributes(ByteBufferPoolDefinition.ATTRIBUTES.stream())); } builder.addChild(builder(BufferCacheDefinition.PATH_ELEMENT).addAttributes(BufferCacheDefinition.ATTRIBUTES.stream())); builder.addChild(builder(ServerDefinition.PATH_ELEMENT).addAttributes(ServerDefinition.ATTRIBUTES.stream()) .addChild(ajpListenerBuilder(schema)) .addChild(httpListenerBuilder(schema)) .addChild(httpsListenerBuilder(schema)) .addChild(hostBuilder(schema)) ); builder.addChild(servletContainerBuilder(schema)); builder.addChild(handlersBuilder(schema)); builder.addChild(PersistentResourceXMLDescription.builder(FilterDefinitions.PATH_ELEMENT).setXmlElementName(Constants.FILTERS).setNoAddOperation(true) .addChild(builder(RequestLimitHandlerDefinition.PATH_ELEMENT).addAttributes(RequestLimitHandlerDefinition.ATTRIBUTES.stream())) .addChild(builder(ResponseHeaderFilterDefinition.PATH_ELEMENT).addAttributes(ResponseHeaderFilterDefinition.ATTRIBUTES.stream())) .addChild(builder(GzipFilterDefinition.PATH_ELEMENT)) .addChild(builder(ErrorPageDefinition.PATH_ELEMENT).addAttributes(ErrorPageDefinition.ATTRIBUTES.stream())) .addChild(modClusterBuilder(schema)) .addChild(builder(CustomFilterDefinition.PATH_ELEMENT).addAttributes(CustomFilterDefinition.ATTRIBUTES.stream()).setXmlElementName("filter")) .addChild(builder(ExpressionFilterDefinition.PATH_ELEMENT).addAttributes(ExpressionFilterDefinition.ATTRIBUTES.stream())) .addChild(builder(RewriteFilterDefinition.PATH_ELEMENT).addAttributes(RewriteFilterDefinition.ATTRIBUTES.stream())) ); if (schema.since(UndertowSubsystemSchema.VERSION_4_0)) { builder.addChild(applicationSecurityDomainBuilder(schema)); } //here to make sure we always add filters & handlers path to mgmt model builder.setAdditionalOperationsGenerator((address, addOperation, operations) -> { operations.add(Util.createAddOperation(address.append(FilterDefinitions.PATH_ELEMENT))); operations.add(Util.createAddOperation(address.append(HandlerDefinitions.PATH_ELEMENT))); }); Stream<AttributeDefinition> attributes = UndertowRootDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_12_0)) { attributes = attributes.filter(Predicate.isEqual(UndertowRootDefinition.OBFUSCATE_SESSION_ROUTE).negate()); } attributes.forEach(builder::addAttribute); return builder.build(); } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder ajpListenerBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(AjpListenerResourceDefinition.PATH_ELEMENT); Stream<AttributeDefinition> attributes = AjpListenerResourceDefinition.ATTRIBUTES.stream(); Stream.concat(listenerAttributes(schema), attributes).forEach(builder::addAttribute); return builder; } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder httpListenerBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(HttpListenerResourceDefinition.PATH_ELEMENT); Stream<AttributeDefinition> attributes = HttpListenerResourceDefinition.ATTRIBUTES.stream(); // Reproduce attribute order of the previous parser implementation Stream.of(listenerAttributes(schema), attributes, httpListenerAttributes(schema)).flatMap(Function.identity()).forEach(builder::addAttribute); return builder; } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder httpsListenerBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(HttpsListenerResourceDefinition.PATH_ELEMENT); Stream<AttributeDefinition> attributes = HttpsListenerResourceDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { attributes = attributes.filter(Predicate.isEqual(HttpsListenerResourceDefinition.SSL_CONTEXT).negate()); } Stream<AttributeDefinition> httpListenerAttributes = httpListenerAttributes(schema); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { httpListenerAttributes = httpListenerAttributes.filter(Predicate.not(Set.of(AbstractHttpListenerResourceDefinition.CERTIFICATE_FORWARDING, AbstractHttpListenerResourceDefinition.PROXY_ADDRESS_FORWARDING)::contains)); } // Reproduce attribute order of the previous parser implementation Stream.of(listenerAttributes(schema), attributes, httpListenerAttributes).flatMap(Function.identity()).forEach(builder::addAttribute); return builder; } private static Stream<AttributeDefinition> httpListenerAttributes(UndertowSubsystemSchema schema) { Stream<AttributeDefinition> attributes = AbstractHttpListenerResourceDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { attributes = attributes.filter(Predicate.isEqual(AbstractHttpListenerResourceDefinition.REQUIRE_HOST_HTTP11).negate()); } if (!schema.since(UndertowSubsystemSchema.VERSION_6_0)) { attributes = attributes.filter(Predicate.isEqual(AbstractHttpListenerResourceDefinition.PROXY_PROTOCOL).negate()); } return attributes; } private static Stream<AttributeDefinition> listenerAttributes(UndertowSubsystemSchema schema) { Stream<AttributeDefinition> attributes = ListenerResourceDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { attributes = attributes.filter(Predicate.isEqual(ListenerResourceDefinition.RFC6265_COOKIE_VALIDATION).negate()); } if (!schema.since(UndertowSubsystemSchema.VERSION_6_0)) { attributes = attributes.filter(Predicate.isEqual(ListenerResourceDefinition.ALLOW_UNESCAPED_CHARACTERS_IN_URL).negate()); } return attributes; } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder hostBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(HostDefinition.PATH_ELEMENT); builder.addChild(builder(LocationDefinition.PATH_ELEMENT).addAttributes(LocationDefinition.ATTRIBUTES.stream()) .addChild(filterRefBuilder()) ); builder.addChild(builder(AccessLogDefinition.PATH_ELEMENT).addAttributes(AccessLogDefinition.ATTRIBUTES.stream())); if (schema.since(UndertowSubsystemSchema.VERSION_9_0)) { builder.addChild(builder(ConsoleAccessLogDefinition.PATH_ELEMENT).addAttributes(ConsoleAccessLogDefinition.ATTRIBUTES.stream())); } builder.addChild(filterRefBuilder()); builder.addChild(builder(SingleSignOnDefinition.PATH_ELEMENT).addAttributes(Attribute.stream(SingleSignOnDefinition.Attribute.class))); if (schema.since(UndertowSubsystemSchema.VERSION_4_0)) { builder.addChild(builder(HttpInvokerDefinition.PATH_ELEMENT).addAttributes(HttpInvokerDefinition.ATTRIBUTES.stream())); } Stream<AttributeDefinition> attributes = HostDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_6_0)) { attributes = attributes.filter(Predicate.isEqual(HostDefinition.QUEUE_REQUESTS_ON_START).negate()); } attributes.forEach(builder::addAttribute); return builder; } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder filterRefBuilder() { return builder(FilterRefDefinition.PATH_ELEMENT).addAttributes(FilterRefDefinition.ATTRIBUTES.stream()); } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder servletContainerBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(ServletContainerDefinition.PATH_ELEMENT); builder.addChild(builder(JspDefinition.PATH_ELEMENT).addAttributes(JspDefinition.ATTRIBUTES.stream()).setXmlElementName(Constants.JSP_CONFIG)); if (schema.since(UndertowSubsystemSchema.VERSION_14_0)) { builder.addChild(builder(AffinityCookieDefinition.PATH_ELEMENT).addAttributes(AffinityCookieDefinition.ATTRIBUTES.stream())); } builder.addChild(builder(SessionCookieDefinition.PATH_ELEMENT).addAttributes(SessionCookieDefinition.ATTRIBUTES.stream())); builder.addChild(builder(PersistentSessionsDefinition.PATH_ELEMENT).addAttributes(PersistentSessionsDefinition.ATTRIBUTES.stream())); builder.addChild(websocketsBuilder(schema)); builder.addChild(builder(MimeMappingDefinition.PATH_ELEMENT).addAttributes(MimeMappingDefinition.ATTRIBUTES.stream()).setXmlWrapperElement("mime-mappings")); builder.addChild(builder(WelcomeFileDefinition.PATH_ELEMENT).setXmlWrapperElement("welcome-files")); builder.addChild(builder(CrawlerSessionManagementDefinition.PATH_ELEMENT).addAttributes(CrawlerSessionManagementDefinition.ATTRIBUTES.stream())); Stream<AttributeDefinition> attributes = ServletContainerDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { attributes = attributes.filter(Predicate.not(Set.of(ServletContainerDefinition.DISABLE_FILE_WATCH_SERVICE, ServletContainerDefinition.DISABLE_SESSION_ID_REUSE)::contains)); } if (!schema.since(UndertowSubsystemSchema.VERSION_5_0)) { attributes = attributes.filter(Predicate.not(Set.of(ServletContainerDefinition.FILE_CACHE_MAX_FILE_SIZE, ServletContainerDefinition.FILE_CACHE_METADATA_SIZE, ServletContainerDefinition.FILE_CACHE_TIME_TO_LIVE)::contains)); } if (!schema.since(UndertowSubsystemSchema.VERSION_6_0)) { attributes = attributes.filter(Predicate.isEqual(ServletContainerDefinition.DEFAULT_COOKIE_VERSION).negate()); } if (!schema.since(UndertowSubsystemSchema.VERSION_10_0)) { attributes = attributes.filter(Predicate.isEqual(ServletContainerDefinition.PRESERVE_PATH_ON_FORWARD).negate()); } attributes.forEach(builder::addAttribute); return builder; } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder websocketsBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(WebsocketsDefinition.PATH_ELEMENT); Stream<AttributeDefinition> attributes = WebsocketsDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { attributes = attributes.filter(Predicate.not(Set.of(WebsocketsDefinition.PER_MESSAGE_DEFLATE, WebsocketsDefinition.DEFLATER_LEVEL)::contains)); } attributes.forEach(builder::addAttribute); return builder; } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder handlersBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(HandlerDefinitions.PATH_ELEMENT).setXmlElementName(Constants.HANDLERS).setNoAddOperation(true); builder.addChild(builder(FileHandlerDefinition.PATH_ELEMENT).addAttributes(FileHandlerDefinition.ATTRIBUTES.stream())); Stream<AttributeDefinition> reverseProxyHandlerAttributes = ReverseProxyHandlerDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { reverseProxyHandlerAttributes = reverseProxyHandlerAttributes.filter(Predicate.isEqual(ReverseProxyHandlerDefinition.MAX_RETRIES).negate()); } Stream<AttributeDefinition> reverseProxyHandlerHostAttributes = ReverseProxyHandlerHostDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { reverseProxyHandlerHostAttributes = reverseProxyHandlerHostAttributes.filter(Predicate.not(Set.of(ReverseProxyHandlerHostDefinition.SSL_CONTEXT, ReverseProxyHandlerHostDefinition.ENABLE_HTTP2)::contains)); } builder.addChild(builder(ReverseProxyHandlerDefinition.PATH_ELEMENT).addAttributes(reverseProxyHandlerAttributes) .addChild(builder(ReverseProxyHandlerHostDefinition.PATH_ELEMENT).addAttributes(ReverseProxyHandlerHostDefinition.ATTRIBUTES.stream()).setXmlElementName(Constants.HOST)) ); return builder; } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder modClusterBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(ModClusterDefinition.PATH_ELEMENT); if (schema.since(UndertowSubsystemSchema.VERSION_10_0)) { builder.addChild(builder(NoAffinityResourceDefinition.PATH).setXmlElementName(Constants.NO_AFFINITY)); builder.addChild(builder(SingleAffinityResourceDefinition.PATH).setXmlElementName(Constants.SINGLE_AFFINITY)); builder.addChild(builder(RankedAffinityResourceDefinition.PATH).addAttributes(Attribute.stream(RankedAffinityResourceDefinition.Attribute.class)).setXmlElementName(Constants.RANKED_AFFINITY)); } Stream<AttributeDefinition> attributes = ModClusterDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_4_0)) { attributes = attributes.filter(Predicate.not(Set.of(ModClusterDefinition.FAILOVER_STRATEGY, ModClusterDefinition.SSL_CONTEXT, ModClusterDefinition.MAX_RETRIES)::contains)); } attributes.forEach(builder::addAttribute); return builder; } private static PersistentResourceXMLDescription.PersistentResourceXMLBuilder applicationSecurityDomainBuilder(UndertowSubsystemSchema schema) { PersistentResourceXMLDescription.PersistentResourceXMLBuilder builder = builder(ApplicationSecurityDomainDefinition.PATH_ELEMENT).setXmlWrapperElement(Constants.APPLICATION_SECURITY_DOMAINS); Stream<AttributeDefinition> ssoAttributes = Stream.concat(Attribute.stream(ApplicationSecurityDomainSingleSignOnDefinition.Attribute.class), Attribute.stream(SingleSignOnDefinition.Attribute.class)); builder.addChild(builder(SingleSignOnDefinition.PATH_ELEMENT).addAttributes(ssoAttributes)); Stream<AttributeDefinition> attributes = ApplicationSecurityDomainDefinition.ATTRIBUTES.stream(); if (!schema.since(UndertowSubsystemSchema.VERSION_7_0)) { attributes = attributes.filter(Predicate.isEqual(ApplicationSecurityDomainDefinition.SECURITY_DOMAIN).negate()); } if (!schema.since(UndertowSubsystemSchema.VERSION_8_0)) { attributes = attributes.filter(Predicate.not(Set.of(ApplicationSecurityDomainDefinition.ENABLE_JASPI, ApplicationSecurityDomainDefinition.INTEGRATED_JASPI)::contains)); } attributes.forEach(builder::addAttribute); return builder; } }
18,730
66.377698
234
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/WelcomeFileDefinition.java
/* * 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.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredAddStepHandler; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.SimpleResourceDefinition; import java.util.Collection; import java.util.List; /** * Global welcome file definition * * @author Stuart Douglas */ class WelcomeFileDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.WELCOME_FILE); WelcomeFileDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey())) .setAddHandler(new ReloadRequiredAddStepHandler()) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) ); } @Override public Collection<AttributeDefinition> getAttributes() { return List.of(); } }
2,112
37.418182
121
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/DiskBasedModularPersistentSessionManager.java
/* * 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.SessionPersistenceManager; 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.modules.ModuleLoader; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; 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; import java.util.function.Consumer; import java.util.function.Supplier; /** * Persistent session manager that stores persistent session information to disk * * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class DiskBasedModularPersistentSessionManager extends AbstractPersistentSessionManager { private final String path; private final String pathRelativeTo; private final Supplier<PathManager> pathManager; private File baseDir; private PathManager.Callback.Handle callbackHandle; DiskBasedModularPersistentSessionManager(final Consumer<SessionPersistenceManager> serviceConsumer, final Supplier<ModuleLoader> moduleLoader, final Supplier<PathManager> pathManager, final String path, final String pathRelativeTo) { super(serviceConsumer, moduleLoader); this.pathManager = pathManager; this.path = path; this.pathRelativeTo = pathRelativeTo; } @Override public void stop(final StopContext stopContext) { super.stop(stopContext); if (callbackHandle != null) { callbackHandle.remove(); } } @Override public void start(final StartContext startContext) throws StartException { super.start(startContext); if (pathRelativeTo != null) { callbackHandle = pathManager.get().registerCallback(pathRelativeTo, PathManager.ReloadServerCallback.create(), PathManager.Event.UPDATED, PathManager.Event.REMOVED); } baseDir = new File(pathManager.get().resolveRelativePathEntry(path, pathRelativeTo)); if (!baseDir.exists() && !baseDir.mkdirs()) { throw UndertowLogger.ROOT_LOGGER.failedToCreatePersistentSessionDir(baseDir); } if (!baseDir.isDirectory()) { throw UndertowLogger.ROOT_LOGGER.invalidPersistentSessionDir(baseDir); } } @Override protected void persistSerializedSessions(String deploymentName, Map<String, SessionEntry> 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<String, SessionEntry> 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<String, SessionEntry>) unMarshaller.readObject(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } finally { unMarshaller.finish(); } } finally { unMarshaller.close(); } } finally { IoUtils.safeClose(in); } } }
5,364
38.160584
177
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpListenerResourceDefinition.java
/* * 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.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.SimpleResourceDefinition; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. * @author Richard Achmatowicz (c) 2020 Red Hat Inc. */ public class HttpListenerResourceDefinition extends AbstractHttpListenerResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.HTTP_LISTENER); static final List<AttributeDefinition> ATTRIBUTES = List.of(REDIRECT_SOCKET); HttpListenerResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(Constants.LISTENER)) .setCapabilities(HTTP_UPGRADE_REGISTRY_CAPABILITY), HttpListenerAdd::new); } @Override public Collection<AttributeDefinition> getAttributes() { List<AttributeDefinition> attributes = new ArrayList<>(ListenerResourceDefinition.ATTRIBUTES.size() + AbstractHttpListenerResourceDefinition.ATTRIBUTES.size() + ATTRIBUTES.size()); attributes.addAll(ListenerResourceDefinition.ATTRIBUTES); attributes.addAll(AbstractHttpListenerResourceDefinition.ATTRIBUTES); attributes.addAll(ATTRIBUTES); return Collections.unmodifiableCollection(attributes); } }
2,525
43.315789
188
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ConsoleRedirectService.java
/* * 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.Supplier; import java.net.InetAddress; import java.net.InetSocketAddress; 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; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * A service to setup a redirect for the web administration console. * * @author <a href="mailto:[email protected]">James R. Perkins</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final 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 Supplier<HttpManagement> httpManagement; private final Supplier<Host> host; ConsoleRedirectService(final Supplier<HttpManagement> httpManagement, final Supplier<Host> host) { this.httpManagement = httpManagement; this.host = host; } @Override public void start(final StartContext startContext) { final Host host = this.host.get(); UndertowLogger.ROOT_LOGGER.debugf("Starting console redirect for %s", host.getName()); final HttpManagement httpManagement = this.httpManagement != null ? this.httpManagement.get() : null; 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 = this.host.get(); UndertowLogger.ROOT_LOGGER.debugf("Stopping console redirect for %s", host.getName()); host.unregisterHandler(CONSOLE_PATH); } 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) { InetAddress destinationAddress = exchange.getDestinationAddress().getAddress(); if (destinationAddress == null && exchange.getDestinationAddress().isUnresolved()) { destinationAddress = new InetSocketAddress(exchange.getDestinationAddress().getHostName(), exchange.getDestinationAddress().getPort()).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 != null && 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; } } }
7,801
44.625731
177
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/CookieConfig.java
/* * 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; /** * Configuration object for a Cookie. * The config can be overridden on a per-app basis, and may not be present. * * @author Stuart Douglas */ public class CookieConfig { private final String name; private final String domain; private final Boolean httpOnly; private final Boolean secure; private final Integer maxAge; public CookieConfig(final String name, final String domain, final Boolean httpOnly, final Boolean secure, final Integer maxAge) { this.name = name; this.domain = domain; this.httpOnly = httpOnly; this.secure = secure; this.maxAge = maxAge; } public String getName() { return name; } public String getDomain() { return domain; } public Boolean getHttpOnly() { return httpOnly; } public Boolean getSecure() { return secure; } public Integer getMaxAge() { return maxAge; } }
2,018
29.590909
133
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpListenerWorkerAttributeWriteHandler.java
/* * 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.logging.Level; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.registry.Resource; import org.jboss.dmr.ModelNode; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * http/https write handler for worker attribute. * * @author baranowb * */ public class HttpListenerWorkerAttributeWriteHandler extends ReloadRequiredWriteAttributeHandler { public HttpListenerWorkerAttributeWriteHandler(AttributeDefinition... definitions) { super(definitions); // TODO Auto-generated constructor stub } @Override protected void finishModelStage(OperationContext context, ModelNode operation, String attributeName, ModelNode newValue, ModelNode oldValue, Resource model) throws OperationFailedException { super.finishModelStage(context, operation, attributeName, newValue, oldValue, model); context.addResponseWarning(Level.WARNING, UndertowLogger.ROOT_LOGGER.workerValueInHTTPListenerMustMatchRemoting()); } }
2,275
38.241379
124
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpListenerService.java
/* * 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 java.util.function.Consumer; import io.undertow.UndertowOptions; import io.undertow.server.ListenerRegistry; import io.undertow.server.OpenListener; import io.undertow.server.handlers.ChannelUpgradeHandler; import io.undertow.server.handlers.ProxyPeerAddressHandler; import io.undertow.server.handlers.SSLHeaderHandler; import io.undertow.server.protocol.http.HttpOpenListener; import io.undertow.server.protocol.http2.Http2UpgradeHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.network.NetworkUtils; import org.jboss.as.server.deployment.DelegatingSupplier; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceName; 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; import static org.wildfly.extension.undertow.HttpListenerResourceDefinition.HTTP_UPGRADE_REGISTRY_CAPABILITY; /** * @author Stuart Douglas * @author Tomaz Cerar * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class HttpListenerService extends ListenerService { private volatile AcceptingChannel<StreamConnection> server; private final ChannelUpgradeHandler httpUpgradeHandler = new ChannelUpgradeHandler(); /** * @deprecated Replaced by HTTP_UPGRADE_REGISTRY.getCapabilityServiceName() */ @Deprecated protected final DelegatingSupplier<ListenerRegistry> httpListenerRegistry = new DelegatingSupplier<>(); static final ServiceName HTTP_UPGRADE_REGISTRY = ServiceName.JBOSS.append("http-upgrade-registry"); static final String PROTOCOL = "http"; private final String serverName; private final PathAddress address ; public HttpListenerService(final Consumer<ListenerService> serviceConsumer, final PathAddress address, final String serverName, OptionMap listenerOptions, OptionMap socketOptions, boolean certificateForwarding, boolean proxyAddressForwarding, boolean proxyProtocol) { super(serviceConsumer, address.getLastElement().getValue(), listenerOptions, socketOptions, proxyProtocol); this.address = address; this.serverName = serverName; addWrapperHandler(handler -> { httpUpgradeHandler.setNonUpgradeHandler(handler); return httpUpgradeHandler; }); if(listenerOptions.get(UndertowOptions.ENABLE_HTTP2, false)) { addWrapperHandler(Http2UpgradeHandler::new); } if (certificateForwarding) { addWrapperHandler(SSLHeaderHandler::new); } if (proxyAddressForwarding) { addWrapperHandler(ProxyPeerAddressHandler::new); } } @Override protected OpenListener createOpenListener() { return new HttpOpenListener(getBufferPool().get(), OptionMap.builder().addAll(commonOptions).addAll(listenerOptions).set(UndertowOptions.ENABLE_STATISTICS, getUndertowService().isStatisticsEnabled()).getMap()); } @Override public boolean isSecure() { return false; } @Override protected void preStart(final StartContext context) { //adds the HTTP upgrade service //TODO: have a bit more of a think about how we handle this final ServiceBuilder<?> sb = context.getChildTarget().addService(HTTP_UPGRADE_REGISTRY_CAPABILITY.getCapabilityServiceName(address)); final Consumer<Object> serviceConsumer = sb.provides(HTTP_UPGRADE_REGISTRY_CAPABILITY.getCapabilityServiceName(address), HTTP_UPGRADE_REGISTRY.append(getName())); sb.setInstance(Service.newInstance(serviceConsumer, httpUpgradeHandler)); sb.install(); ListenerRegistry.Listener listener = new ListenerRegistry.Listener(getProtocol(), getName(), serverName, getBinding().get().getSocketAddress()); listener.setContextInformation("socket-binding", getBinding().get()); httpListenerRegistry.get().addListener(listener); } protected void startListening(XnioWorker worker, InetSocketAddress socketAddress, ChannelListener<AcceptingChannel<StreamConnection>> 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("HTTP", getName(), NetworkUtils.formatIPAddressForURI(boundAddress.getAddress()), boundAddress.getPort()); } @Override protected void cleanFailedStart() { httpListenerRegistry.get().removeListener(getName()); } protected void unregisterBinding() { httpListenerRegistry.get().removeListener(getName()); super.unregisterBinding(); } @Override protected void stopListening() { final InetSocketAddress boundAddress = server.getLocalAddress(InetSocketAddress.class); server.suspendAccepts(); UndertowLogger.ROOT_LOGGER.listenerSuspend("HTTP", getName()); IoUtils.safeClose(server); server = null; UndertowLogger.ROOT_LOGGER.listenerStopped("HTTP", getName(), NetworkUtils.formatIPAddressForURI(boundAddress.getAddress()), boundAddress.getPort()); } @Override public HttpListenerService getValue() throws IllegalStateException, IllegalArgumentException { return this; } public DelegatingSupplier<ListenerRegistry> getHttpListenerRegistry() { return httpListenerRegistry; } @Override public String getProtocol() { return PROTOCOL; } }
6,975
42.6
271
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ListenerService.java
/* * 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.BindException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import javax.net.ssl.SSLContext; import io.undertow.UndertowOptions; import io.undertow.protocols.ssl.UndertowXnioSsl; import io.undertow.connector.ByteBufferPool; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.OpenListener; import io.undertow.server.protocol.proxy.ProxyProtocolOpenListener; import io.undertow.util.StatusCodes; import org.jboss.as.network.ManagedBinding; import org.jboss.as.network.SocketBinding; import org.jboss.as.server.deployment.DelegatingSupplier; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceContainer; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.xnio.ChannelListener; import org.xnio.ChannelListeners; import org.xnio.OptionMap; import org.xnio.Options; import org.xnio.StreamConnection; import org.xnio.XnioWorker; import org.xnio.channels.AcceptingChannel; /** * @author Tomaz Cerar * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public abstract class ListenerService implements Service<UndertowListener>, UndertowListener { protected static final OptionMap commonOptions = OptionMap.builder() .set(Options.TCP_NODELAY, true) .set(Options.REUSE_ADDRESSES, true) .set(Options.BALANCING_TOKENS, 1) .set(Options.BALANCING_CONNECTIONS, 2) .getMap(); protected Consumer<ListenerService> serviceConsumer; protected final DelegatingSupplier<XnioWorker> worker = new DelegatingSupplier<>(); protected final DelegatingSupplier<SocketBinding> binding = new DelegatingSupplier<>(); protected final DelegatingSupplier<SocketBinding> redirectSocket = new DelegatingSupplier<>(); @SuppressWarnings("rawtypes") protected final DelegatingSupplier<ByteBufferPool> bufferPool = new DelegatingSupplier<>(); protected final DelegatingSupplier<Server> serverService = new DelegatingSupplier<>(); private final List<HandlerWrapper> listenerHandlerWrappers = new ArrayList<>(); private final String name; protected final OptionMap listenerOptions; protected final OptionMap socketOptions; protected volatile OpenListener openListener; private volatile boolean enabled; private volatile boolean started; private Consumer<Boolean> statisticsChangeListener; private final boolean proxyProtocol; private volatile HandlerWrapper stoppingWrapper; protected ListenerService(Consumer<ListenerService> serviceConsumer, String name, OptionMap listenerOptions, OptionMap socketOptions, boolean proxyProtocol) { this.serviceConsumer = serviceConsumer; this.name = name; this.listenerOptions = listenerOptions; this.socketOptions = socketOptions; this.proxyProtocol = proxyProtocol; } public DelegatingSupplier<XnioWorker> getWorker() { return worker; } public DelegatingSupplier<SocketBinding> getBinding() { return binding; } public DelegatingSupplier<SocketBinding> getRedirectSocket() { return redirectSocket; } @SuppressWarnings("rawtypes") public DelegatingSupplier<ByteBufferPool> getBufferPool() { return bufferPool; } public DelegatingSupplier<Server> getServerService() { return serverService; } protected UndertowService getUndertowService() { return serverService.get().getUndertowService(); } public String getName() { return name; } @Override public Server getServer() { return this.serverService.get(); } public boolean isEnabled() { return enabled; } protected UndertowXnioSsl getSsl() { return null; } protected OptionMap getSSLOptions(SSLContext sslContext) { return OptionMap.EMPTY; } public synchronized void setEnabled(boolean enabled) { if(started && enabled != this.enabled) { if(enabled) { final InetSocketAddress socketAddress = binding.get().getSocketAddress(); final ChannelListener<AcceptingChannel<StreamConnection>> acceptListener = ChannelListeners.openListenerAdapter(openListener); try { startListening(worker.get(), socketAddress, acceptListener); } catch (IOException e) { throw new RuntimeException(e); } } else { stopListening(); } } this.enabled = enabled; } public abstract boolean isSecure(); protected void registerBinding() { binding.get().getSocketBindings().getNamedRegistry().registerBinding(new ListenerBinding(binding.get())); } protected void unregisterBinding() { final SocketBinding binding = this.binding.get(); binding.getSocketBindings().getNamedRegistry().unregisterBinding(binding.getName()); } protected abstract void preStart(StartContext context); @Override public void start(final StartContext context) throws StartException { started = true; preStart(context); serverService.get().registerListener(this); try { openListener = createOpenListener(); HttpHandler handler = serverService.get().getRoot(); for(HandlerWrapper wrapper : listenerHandlerWrappers) { handler = wrapper.wrap(handler); } openListener.setRootHandler(handler); if(enabled) { final InetSocketAddress socketAddress = binding.get().getSocketAddress(); final ChannelListener<AcceptingChannel<StreamConnection>> acceptListener; if(proxyProtocol) { UndertowXnioSsl xnioSsl = getSsl(); acceptListener = ChannelListeners.openListenerAdapter(new ProxyProtocolOpenListener(openListener, xnioSsl, bufferPool.get(), xnioSsl != null ? getSSLOptions(xnioSsl.getSslContext()) : null)); } else { acceptListener = ChannelListeners.openListenerAdapter(openListener); } startListening(worker.get(), socketAddress, acceptListener); } registerBinding(); } catch (IOException e) { cleanFailedStart(); if (e instanceof BindException) { final StringBuilder sb = new StringBuilder().append(e.getLocalizedMessage()); final InetSocketAddress socketAddress = binding.get().getSocketAddress(); if (socketAddress != null) sb.append(" ").append(socketAddress); throw new StartException(sb.toString()); } else { throw UndertowLogger.ROOT_LOGGER.couldNotStartListener(name, e); } } statisticsChangeListener = (enabled) -> { OptionMap options = openListener.getUndertowOptions(); OptionMap.Builder builder = OptionMap.builder().addAll(options); builder.set(UndertowOptions.ENABLE_STATISTICS, enabled); openListener.setUndertowOptions(builder.getMap()); }; getUndertowService().registerStatisticsListener(statisticsChangeListener); final ServiceContainer container = context.getController().getServiceContainer(); this.stoppingWrapper = new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { return new HttpHandler() { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { //graceful shutdown is handled by the host service, so if the container is actually shutting down there //is a brief window where this will result in a 404 rather than a 503 //even without graceful shutdown we start returning 503 once the container has started shutting down if(container.isShutdown()) { exchange.setStatusCode(StatusCodes.SERVICE_UNAVAILABLE); return; } handler.handleRequest(exchange); } }; } }; addWrapperHandler(stoppingWrapper); serviceConsumer.accept(this); } protected abstract void cleanFailedStart(); @Override public void stop(StopContext context) { serviceConsumer.accept(null); started = false; serverService.get().unregisterListener(this); if(enabled) { stopListening(); } unregisterBinding(); getUndertowService().unregisterStatisticsListener(statisticsChangeListener); statisticsChangeListener = null; listenerHandlerWrappers.remove(stoppingWrapper); stoppingWrapper = null; } void addWrapperHandler(HandlerWrapper wrapper){ listenerHandlerWrappers.add(wrapper); } public OpenListener getOpenListener() { return openListener; } protected abstract OpenListener createOpenListener(); abstract void startListening(XnioWorker worker, InetSocketAddress socketAddress, ChannelListener<AcceptingChannel<StreamConnection>> acceptListener) throws IOException; abstract void stopListening(); public abstract String getProtocol(); @Override public boolean isShutdown() { final DelegatingSupplier<XnioWorker> workerSupplier = getWorker(); XnioWorker worker = workerSupplier != null ? workerSupplier.get() : null; return worker == null || worker.isShutdown(); } @Override public SocketBinding getSocketBinding() { return binding.get(); } private static class ListenerBinding implements ManagedBinding { private final SocketBinding binding; private ListenerBinding(final SocketBinding binding) { this.binding = binding; } @Override public String getSocketBindingName() { return binding.getName(); } @Override public InetSocketAddress getBindAddress() { return binding.getSocketAddress(); } @Override public void close() throws IOException { } } }
11,777
36.037736
211
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ServerAdd.java
/* * 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.ServerDefinition.SERVER_CAPABILITY; import java.util.ServiceLoader; import java.util.function.Consumer; import java.util.function.Supplier; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; 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.PathElement; import org.jboss.as.controller.registry.Resource; import org.jboss.as.web.host.CommonWebServer; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.wildfly.extension.undertow.session.DistributableServerRuntimeHandler; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class ServerAdd extends AbstractAddStepHandler { ServerAdd() { super(new Parameters() .addAttribute(ServerDefinition.ATTRIBUTES) ); } @Override protected void performRuntime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { PathAddress address = context.getCurrentAddress(); final ModelNode parentModel = context.readResourceFromRoot(address.getParent(), false).getModel(); final String name = context.getCurrentAddressValue(); final String defaultHost = ServerDefinition.DEFAULT_HOST.resolveModelAttribute(context, resource.getModel()).asString(); final String servletContainer = ServerDefinition.SERVLET_CONTAINER.resolveModelAttribute(context, resource.getModel()).asString(); final String defaultServerName = UndertowRootDefinition.DEFAULT_SERVER.resolveModelAttribute(context, parentModel).asString(); boolean isDefaultServer = name.equals(defaultServerName); final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(SERVER_CAPABILITY); final Consumer<Server> sConsumer = isDefaultServer ? sb.provides(SERVER_CAPABILITY, UndertowService.DEFAULT_SERVER) : sb.provides(SERVER_CAPABILITY); final Supplier<ServletContainerService> scsSupplier = sb.requiresCapability(Capabilities.CAPABILITY_SERVLET_CONTAINER, ServletContainerService.class, servletContainer); final Supplier<UndertowService> usSupplier = sb.requiresCapability(Capabilities.CAPABILITY_UNDERTOW, UndertowService.class); sb.setInstance(new Server(sConsumer, scsSupplier, usSupplier, name, defaultHost)); sb.install(); if (isDefaultServer) { //only install for default server final CapabilityServiceBuilder<?> csb = context.getCapabilityServiceTarget().addCapability(CommonWebServer.CAPABILITY); final Consumer<WebServerService> wssConsumer = csb.provides(CommonWebServer.CAPABILITY, CommonWebServer.SERVICE_NAME); final Supplier<Server> sSupplier = csb.requiresCapability(Capabilities.CAPABILITY_SERVER, Server.class, name); csb.setInstance(new WebServerService(wssConsumer, sSupplier)); csb.setInitialMode(ServiceController.Mode.PASSIVE); addCommonHostListenerDeps(context, csb, HttpListenerResourceDefinition.PATH_ELEMENT); addCommonHostListenerDeps(context, csb, AjpListenerResourceDefinition.PATH_ELEMENT); addCommonHostListenerDeps(context, csb, HttpsListenerResourceDefinition.PATH_ELEMENT); csb.install(); } for (DistributableServerRuntimeHandler handler : ServiceLoader.load(DistributableServerRuntimeHandler.class, DistributableServerRuntimeHandler.class.getClassLoader())) { handler.execute(context, name); } } /** * <strong>TODO</strong> WFCORE-6176 Update AbstractAddHandler and its Parameters class to support a more fit-to-use * API for handling this kind of use case, i.e. to register a per-capability function to override the default * registration logic. * <p> * Replaces the superclass implementation in order to only register {@link CommonWebServer#CAPABILITY} if * the resource's name matches the containing subsystems {@link UndertowRootDefinition#DEFAULT_SERVER} value. * <p> * <strong>IMPORTANT</strong> This implemenation deliberately doesn't call the superclass implementation * as we don't want it to always register {@link CommonWebServer#CAPABILITY}. So we directly handle all * registration here. * * @param context – the context. Will not be null * @param operation – the operation that is executing Will not be null * @param resource – the resource that has been added. Will reflect any updates made by populateModel(OperationContext, ModelNode, Resource). Will not be null */ @Override protected void recordCapabilitiesAndRequirements(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { context.registerCapability(SERVER_CAPABILITY.fromBaseCapability(context.getCurrentAddress())); // We currently don't have any attributes that reference capabilities, but we have this code in case that changes // since we are not calling the superclass code. ModelNode model = resource.getModel(); for (AttributeDefinition ad : getAttributes()) { if (model.hasDefined(ad.getName()) || ad.hasCapabilityRequirements()) { ad.addCapabilityRequirements(context, resource, model.get(ad.getName())); } } ModelNode parentModel = context.readResourceFromRoot(context.getCurrentAddress().getParent(), false).getModel(); final String defaultServerName = UndertowRootDefinition.DEFAULT_SERVER.resolveModelAttribute(context, parentModel).asString(); boolean isDefaultServer = context.getCurrentAddressValue().equals(defaultServerName); if (isDefaultServer) { context.registerCapability(CommonWebServer.CAPABILITY); } } private void addCommonHostListenerDeps(OperationContext context, ServiceBuilder<?> builder, final PathElement listenerPath) { ModelNode listeners = Resource.Tools.readModel(context.readResource(PathAddress.pathAddress(listenerPath)), 1); if (listeners.isDefined()) { for (Property p : listeners.asPropertyList()) { for (Property listener : p.getValue().asPropertyList()) { builder.requires(ListenerResourceDefinition.LISTENER_CAPABILITY.getCapabilityServiceName(listener.getName())); } } } } }
7,886
54.153846
177
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AccessLogDefinition.java
/* * 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.List; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; 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.DynamicNameMappers; 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 PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.ACCESS_LOG); static final RuntimeCapability<Void> ACCESS_LOG_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_ACCESS_LOG, true, AccessLogService.class) .setDynamicNameMapper(DynamicNameMappers.GRAND_PARENT) .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(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(ModelNode.FALSE) .setAllowExpression(true) .setRestartAllServices() .build(); protected static final SimpleAttributeDefinition EXTENDED = new SimpleAttributeDefinitionBuilder(Constants.EXTENDED, ModelType.BOOLEAN, true) .setDefaultValue(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<AttributeDefinition> ATTRIBUTES = List.of( // IMPORTANT -- keep these in xsd order as this order controls marshalling WORKER, PATTERN, PREFIX, SUFFIX, ROTATE, DIRECTORY, USE_SERVER_LOG, RELATIVE_TO, EXTENDED, PREDICATE ); private final List<AccessConstraintDefinition> accessConstraints; AccessLogDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getValue())) .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<AccessConstraintDefinition> getAccessConstraints() { return accessConstraints; } @Override public Collection<AttributeDefinition> getAttributes() { //noinspection unchecked return (Collection) ATTRIBUTES; } }
7,132
46.238411
159
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowRootDefinition.java
/* * 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.SUBSYSTEM; import static org.wildfly.extension.undertow.Capabilities.CAPABILITY_HTTP_INVOKER; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import io.undertow.server.handlers.PathHandler; import org.jboss.as.controller.AbstractWriteAttributeHandler; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.ReloadRequiredRemoveStepHandler; import org.jboss.as.controller.ReloadRequiredWriteAttributeHandler; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; 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.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.ValueExpression; import org.jboss.msc.service.ServiceController; import org.wildfly.extension.undertow.filters.FilterDefinitions; import org.wildfly.extension.undertow.handlers.HandlerDefinitions; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. */ class UndertowRootDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(SUBSYSTEM, UndertowExtension.SUBSYSTEM_NAME); static final RuntimeCapability<Void> UNDERTOW_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_UNDERTOW, false, UndertowService.class) .build(); static final RuntimeCapability<Void> HTTP_INVOKER_RUNTIME_CAPABILITY = RuntimeCapability.Builder.of(CAPABILITY_HTTP_INVOKER, false, PathHandler.class) .build(); protected static final SimpleAttributeDefinition DEFAULT_SERVLET_CONTAINER = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_SERVLET_CONTAINER, ModelType.STRING, true) .setRestartAllServices() .setDefaultValue(new ModelNode("default")) .setCapabilityReference(UNDERTOW_CAPABILITY, Capabilities.CAPABILITY_SERVLET_CONTAINER) .build(); protected static final SimpleAttributeDefinition DEFAULT_SERVER = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_SERVER, ModelType.STRING, true) .setRestartAllServices() .setDefaultValue(new ModelNode("default-server")) .setCapabilityReference(UNDERTOW_CAPABILITY, Capabilities.CAPABILITY_SERVER) .build(); protected static final SimpleAttributeDefinition DEFAULT_VIRTUAL_HOST = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_VIRTUAL_HOST, ModelType.STRING, true) .setRestartAllServices() .setDefaultValue(new ModelNode("default-host")) .setCapabilityReference(UNDERTOW_CAPABILITY, Capabilities.CAPABILITY_HOST, DEFAULT_SERVER) .build(); protected static final SimpleAttributeDefinition INSTANCE_ID = new SimpleAttributeDefinitionBuilder(Constants.INSTANCE_ID, ModelType.STRING, true) .setRestartAllServices() .setAllowExpression(true) .setDefaultValue(new ModelNode().set(new ValueExpression("${jboss.node.name}"))) .build(); protected static final SimpleAttributeDefinition OBFUSCATE_SESSION_ROUTE = new SimpleAttributeDefinitionBuilder(Constants.OBFUSCATE_SESSION_ROUTE, ModelType.BOOLEAN, true) .setRestartAllServices() .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition STATISTICS_ENABLED = new SimpleAttributeDefinitionBuilder(Constants.STATISTICS_ENABLED, ModelType.BOOLEAN, true) .setRestartAllServices() .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition DEFAULT_SECURITY_DOMAIN = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_SECURITY_DOMAIN, ModelType.STRING, true) .setAllowExpression(true) .setDefaultValue(new ModelNode("other")) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SECURITY_DOMAIN_REF) .setRestartAllServices() .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of(DEFAULT_VIRTUAL_HOST, DEFAULT_SERVLET_CONTAINER, DEFAULT_SERVER, INSTANCE_ID, OBFUSCATE_SESSION_ROUTE, STATISTICS_ENABLED, DEFAULT_SECURITY_DOMAIN); private final Set<String> knownApplicationSecurityDomains; UndertowRootDefinition() { this(new CopyOnWriteArraySet<>()); } private UndertowRootDefinition(Set<String> knownApplicationSecurityDomains) { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver()) .setAddHandler(new UndertowSubsystemAdd(knownApplicationSecurityDomains::contains)) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .addCapabilities(UNDERTOW_CAPABILITY, HTTP_INVOKER_RUNTIME_CAPABILITY) ); this.knownApplicationSecurityDomains = knownApplicationSecurityDomains; } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } @Override public List<? extends PersistentResourceDefinition> getChildren() { return List.of( new ByteBufferPoolDefinition(), new BufferCacheDefinition(), new ServerDefinition(), new ServletContainerDefinition(), new HandlerDefinitions(), new FilterDefinitions(), new ApplicationSecurityDomainDefinition(this.knownApplicationSecurityDomains)); } @Override public void registerAttributes(ManagementResourceRegistration resourceRegistration) { ReloadRequiredWriteAttributeHandler handler = new ReloadRequiredWriteAttributeHandler(getAttributes()); for (AttributeDefinition attr : getAttributes()) { if (attr == STATISTICS_ENABLED) { resourceRegistration.registerReadWriteAttribute(attr, null, new AbstractWriteAttributeHandler<Void>(STATISTICS_ENABLED) { @Override protected boolean applyUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode resolvedValue, ModelNode currentValue, HandbackHolder<Void> handbackHolder) throws OperationFailedException { ServiceController<?> controller = context.getServiceRegistry(false).getService(UndertowService.UNDERTOW); if (controller != null) { UndertowService service = (UndertowService) controller.getService(); if (service != null) { service.setStatisticsEnabled(resolvedValue.asBoolean()); } } return false; } @Override protected void revertUpdateToRuntime(OperationContext context, ModelNode operation, String attributeName, ModelNode valueToRestore, ModelNode valueToRevert, Void handback) throws OperationFailedException { ServiceController<?> controller = context.getServiceRegistry(false).getService(UndertowService.UNDERTOW); if (controller != null) { UndertowService service = (UndertowService) controller.getService(); if (service != null) { service.setStatisticsEnabled(valueToRestore.asBoolean()); } } } }); } else { resourceRegistration.registerReadWriteAttribute(attr, null, handler); } } } }
9,795
51.951351
247
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HostAdd.java
/* * 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 java.util.function.Consumer; import java.util.function.Supplier; 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.controller.capability.RuntimeCapability; 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.Mode; import org.jboss.msc.service.ServiceName; import org.wildfly.extension.requestcontroller.RequestController; import org.wildfly.extension.undertow.deployment.DefaultDeploymentMappingProvider; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class HostAdd extends AbstractAddStepHandler { static final HostAdd INSTANCE = new HostAdd(); private HostAdd() { super(HostDefinition.ATTRIBUTES); } @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<String> 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(); Boolean queueRequestsOnStart = null; if (model.hasDefined(HostDefinition.QUEUE_REQUESTS_ON_START.getName())) { queueRequestsOnStart = HostDefinition.QUEUE_REQUESTS_ON_START.resolveModelAttribute(context, model).asBoolean(); } if (!defaultWebModule.equals(HostDefinition.DEFAULT_WEB_MODULE_DEFAULT) || DefaultDeploymentMappingProvider.instance().getMapping(HostDefinition.DEFAULT_WEB_MODULE_DEFAULT) == null) { DefaultDeploymentMappingProvider.instance().addMapping(defaultWebModule, serverName, name); } final ServiceName virtualHostServiceName = HostDefinition.HOST_CAPABILITY.fromBaseCapability(address).getCapabilityServiceName(); final CapabilityServiceBuilder<?> csb = context.getCapabilityServiceTarget().addCapability(HostDefinition.HOST_CAPABILITY); Consumer<Host> hostConsumer; if (isDefaultHost) { addCommonHost(context, aliases, serverName, virtualHostServiceName); final RuntimeCapability<?>[] capabilitiesParam = new RuntimeCapability<?>[] {HostDefinition.HOST_CAPABILITY}; final ServiceName[] serviceNamesParam = new ServiceName[] {UndertowService.virtualHostName(serverName, name), UndertowService.DEFAULT_HOST}; hostConsumer = csb.provides(capabilitiesParam, serviceNamesParam); } else { hostConsumer = csb.provides(HostDefinition.HOST_CAPABILITY, UndertowService.virtualHostName(serverName, name)); } final Supplier<Server> sSupplier = csb.requiresCapability(Capabilities.CAPABILITY_SERVER, Server.class, serverName); final Supplier<UndertowService> usSupplier = csb.requiresCapability(Capabilities.CAPABILITY_UNDERTOW, UndertowService.class); final Supplier<ControlledProcessStateService> cpssSupplier = csb.requires(ControlledProcessStateService.SERVICE_NAME); final Supplier<SuspendController> scSupplier = csb.requires(context.getCapabilityServiceName(Capabilities.REF_SUSPEND_CONTROLLER, SuspendController.class)); csb.setInstance(new Host(hostConsumer, sSupplier, usSupplier, cpssSupplier, scSupplier, name, aliases == null ? new LinkedList<>(): aliases, defaultWebModule, defaultResponseCode, queueRequestsOnStart)); csb.setInitialMode(Mode.ON_DEMAND); csb.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 ServiceBuilder<?> sb = context.getServiceTarget().addService(consoleRedirectName); final Supplier<HttpManagement> hmSupplier = sb.requires(UndertowHttpManagementService.SERVICE_NAME); final Supplier<Host> hSupplier = sb.requires(virtualHostServiceName); sb.setInstance(new ConsoleRedirectService(hmSupplier, hSupplier)); sb.setInitialMode(Mode.PASSIVE); sb.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 ServiceBuilder<?> sb = context.getServiceTarget().addService(consoleRedirectName); final Supplier<Host> hSupplier = sb.requires(virtualHostServiceName); sb.setInstance(new ConsoleRedirectService(null, hSupplier)); sb.setInitialMode(Mode.PASSIVE); sb.install(); } } } private void addCommonHost(OperationContext context, List<String> aliases, String serverName, ServiceName virtualHostServiceName) { final RuntimeCapability<?>[] capabilitiesParam = new RuntimeCapability<?>[] {WebHost.CAPABILITY}; final ServiceName[] serviceNamesParam = new ServiceName[aliases == null ? 1 : aliases.size() + 1]; if (aliases != null) { int i = 0; for (final String alias : aliases) { serviceNamesParam[i++] = WebHost.SERVICE_NAME.append(alias); } } serviceNamesParam[serviceNamesParam.length - 1] = WebHost.SERVICE_NAME.append(context.getCurrentAddressValue()); final boolean rqCapabilityAvailable = context.hasOptionalCapability(Capabilities.REF_REQUEST_CONTROLLER, null, null); final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(WebHost.CAPABILITY); final Consumer<WebHost> whConsumer = sb.provides(capabilitiesParam, serviceNamesParam); final Supplier<Server> sSupplier = sb.requiresCapability(Capabilities.CAPABILITY_SERVER, Server.class, serverName); final Supplier<Host> hSupplier = sb.requires(virtualHostServiceName); final Supplier<RequestController> rcSupplier = rqCapabilityAvailable ? sb.requiresCapability(Capabilities.REF_REQUEST_CONTROLLER, RequestController.class) : null; sb.setInstance(new WebHostService(whConsumer, sSupplier, hSupplier, rcSupplier)); sb.requiresCapability(CommonWebServer.CAPABILITY_NAME, CommonWebServer.class); sb.setInitialMode(Mode.PASSIVE); sb.install(); } }
10,238
59.946429
211
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/SingleSignOnManagerServiceNameProvider.java
/* * 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.msc.service.ServiceName; import org.wildfly.clustering.service.ServiceNameProvider; /** * @author Paul Ferraro */ public class SingleSignOnManagerServiceNameProvider implements ServiceNameProvider { private final ServiceName name; public SingleSignOnManagerServiceNameProvider(String securityDomainName) { this.name = ApplicationSecurityDomainDefinition.APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY.fromBaseCapability(securityDomainName).getCapabilityServiceName().append("sso", "manager"); } @Override public ServiceName getServiceName() { return this.name; } }
1,693
37.5
194
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/InMemoryModularPersistentSessionManager.java
/* * 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.SessionPersistenceManager; import org.jboss.modules.ModuleLoader; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; /** * Persistent session manager that simply stores the session information in a map * * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class InMemoryModularPersistentSessionManager extends AbstractPersistentSessionManager { InMemoryModularPersistentSessionManager(final Consumer<SessionPersistenceManager> serviceConsumer, final Supplier<ModuleLoader> moduleLoader) { super(serviceConsumer, moduleLoader); } /** * The serialized sessions */ private final Map<String, Map<String, SessionEntry>> sessionData = Collections.synchronizedMap(new HashMap<String, Map<String, SessionEntry>>()); @Override protected void persistSerializedSessions(String deploymentName, Map<String, SessionEntry> serializedData) { sessionData.put(deploymentName, serializedData); } @Override protected Map<String, SessionEntry> loadSerializedSessions(String deploymentName) { return sessionData.remove(deploymentName); } }
2,388
38.816667
149
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/SingleSignOnSessionFactoryServiceConfigurator.java
/* * 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.ApplicationSecurityDomainSingleSignOnDefinition.Attribute.CREDENTIAL; import static org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute.KEY_ALIAS; import static org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute.KEY_STORE; import static org.wildfly.extension.undertow.ApplicationSecurityDomainSingleSignOnDefinition.Attribute.SSL_CONTEXT; import java.io.IOException; import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyStore; import java.util.Optional; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import javax.net.ssl.SSLContext; import org.jboss.as.clustering.controller.CommonUnaryRequirement; import org.jboss.as.clustering.controller.CredentialSourceDependency; import org.jboss.as.clustering.controller.ResourceServiceConfigurator; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.dmr.ModelNode; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceTarget; import org.wildfly.clustering.service.CompositeDependency; import org.wildfly.clustering.service.FunctionalService; import org.wildfly.clustering.service.ServiceConfigurator; import org.wildfly.clustering.service.ServiceSupplierDependency; import org.wildfly.clustering.service.SupplierDependency; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.security.credential.PasswordCredential; import org.wildfly.security.credential.source.CredentialSource; import org.wildfly.security.http.util.sso.DefaultSingleSignOnSessionFactory; import org.wildfly.security.http.util.sso.SingleSignOnManager; import org.wildfly.security.http.util.sso.SingleSignOnSessionFactory; import org.wildfly.security.password.interfaces.ClearPassword; /** * @author Paul Ferraro */ public class SingleSignOnSessionFactoryServiceConfigurator extends SingleSignOnSessionFactoryServiceNameProvider implements ResourceServiceConfigurator, Supplier<SingleSignOnSessionFactory> { private final SupplierDependency<SingleSignOnManager> manager; private volatile SupplierDependency<KeyStore> keyStore; private volatile SupplierDependency<SSLContext> sslContext; private volatile SupplierDependency<CredentialSource> credentialSource; private volatile String keyAlias; public SingleSignOnSessionFactoryServiceConfigurator(String securityDomainName) { super(securityDomainName); this.manager = new ServiceSupplierDependency<>(new SingleSignOnManagerServiceNameProvider(securityDomainName)); } @Override public ServiceConfigurator configure(OperationContext context, ModelNode model) throws OperationFailedException { String keyStore = KEY_STORE.resolveModelAttribute(context, model).asString(); this.keyStore = new ServiceSupplierDependency<>(CommonUnaryRequirement.KEY_STORE.getServiceName(context, keyStore)); this.keyAlias = KEY_ALIAS.resolveModelAttribute(context, model).asString(); this.credentialSource = new CredentialSourceDependency(context, CREDENTIAL, model); String sslContext = SSL_CONTEXT.resolveModelAttribute(context, model).asStringOrNull(); this.sslContext = (sslContext != null) ? new ServiceSupplierDependency<>(CommonUnaryRequirement.SSL_CONTEXT.getServiceName(context, sslContext)) : null; return this; } @Override public ServiceBuilder<?> build(ServiceTarget target) { ServiceBuilder<?> builder = target.addService(this.getServiceName()); Consumer<SingleSignOnSessionFactory> factory = new CompositeDependency(this.manager, this.keyStore, this.credentialSource, this.sslContext).register(builder).provides(this.getServiceName()); Service service = new FunctionalService<>(factory, Function.identity(), this); return builder.setInstance(service); } @Override public SingleSignOnSessionFactory get() { KeyStore store = this.keyStore.get(); String alias = this.keyAlias; CredentialSource source = this.credentialSource.get(); try { if (!store.containsAlias(alias)) { throw UndertowLogger.ROOT_LOGGER.missingKeyStoreEntry(alias); } if (!store.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)) { throw UndertowLogger.ROOT_LOGGER.keyStoreEntryNotPrivate(alias); } PasswordCredential credential = source.getCredential(PasswordCredential.class); if (credential == null) { throw UndertowLogger.ROOT_LOGGER.missingCredential(source.toString()); } ClearPassword password = credential.getPassword(ClearPassword.class); if (password == null) { throw UndertowLogger.ROOT_LOGGER.credentialNotClearPassword(credential.toString()); } KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) store.getEntry(alias, new KeyStore.PasswordProtection(password.getPassword())); KeyPair keyPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey()); Optional<SSLContext> context = Optional.ofNullable(this.sslContext).map(dependency -> dependency.get()); return new DefaultSingleSignOnSessionFactory(this.manager.get(), keyPair, connection -> context.ifPresent(ctx -> connection.setSSLSocketFactory(ctx.getSocketFactory()))); } catch (GeneralSecurityException | IOException e) { throw new IllegalArgumentException(e); } } }
6,811
52.21875
198
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ServletContainerDefinition.java
/* * 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.List; import io.undertow.servlet.api.ServletStackTraces; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.PathElement; 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.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.as.controller.client.helpers.MeasurementUnit; import org.jboss.as.controller.operations.validation.EnumValidator; 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; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ class ServletContainerDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SERVLET_CONTAINER); static final RuntimeCapability<Void> SERVLET_CONTAINER_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_SERVLET_CONTAINER, true, ServletContainerService.class) .addRequirements(Capabilities.CAPABILITY_UNDERTOW) .build(); protected static final SimpleAttributeDefinition ALLOW_NON_STANDARD_WRAPPERS = new SimpleAttributeDefinitionBuilder(Constants.ALLOW_NON_STANDARD_WRAPPERS, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition DEFAULT_BUFFER_CACHE = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_BUFFER_CACHE, ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(new ModelNode("default")) .build(); protected static final SimpleAttributeDefinition STACK_TRACE_ON_ERROR = new SimpleAttributeDefinitionBuilder(Constants.STACK_TRACE_ON_ERROR, ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(new ModelNode(ServletStackTraces.LOCAL_ONLY.toString())) .setValidator(EnumValidator.create(ServletStackTraces.class)) .setAllowExpression(true) .build(); protected static final SimpleAttributeDefinition DEFAULT_ENCODING = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_ENCODING, ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .build(); protected static final AttributeDefinition USE_LISTENER_ENCODING = new SimpleAttributeDefinitionBuilder(Constants.USE_LISTENER_ENCODING, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final AttributeDefinition IGNORE_FLUSH = new SimpleAttributeDefinitionBuilder(Constants.IGNORE_FLUSH, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final AttributeDefinition EAGER_FILTER_INIT = new SimpleAttributeDefinitionBuilder("eager-filter-initialization", ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final AttributeDefinition DEFAULT_SESSION_TIMEOUT = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_SESSION_TIMEOUT, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setMeasurementUnit(MeasurementUnit.MINUTES) .setDefaultValue(new ModelNode(30)) .build(); //30 minutes protected static final AttributeDefinition DISABLE_CACHING_FOR_SECURED_PAGES = new SimpleAttributeDefinitionBuilder("disable-caching-for-secured-pages", ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.TRUE) .build(); protected static final AttributeDefinition DIRECTORY_LISTING = new SimpleAttributeDefinitionBuilder(Constants.DIRECTORY_LISTING, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .build(); protected static final AttributeDefinition PROACTIVE_AUTHENTICATION = new SimpleAttributeDefinitionBuilder(Constants.PROACTIVE_AUTHENTICATION, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.TRUE) .setAllowExpression(true) .build(); protected static final AttributeDefinition SESSION_ID_LENGTH = new SimpleAttributeDefinitionBuilder(Constants.SESSION_ID_LENGTH, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setValidator(new IntRangeValidator(16, 200, true, true)) .setDefaultValue(new ModelNode(30)) .build(); protected static final AttributeDefinition MAX_SESSIONS = new SimpleAttributeDefinitionBuilder(Constants.MAX_SESSIONS, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .build(); protected static final AttributeDefinition DISABLE_FILE_WATCH_SERVICE = new SimpleAttributeDefinitionBuilder(Constants.DISABLE_FILE_WATCH_SERVICE, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final AttributeDefinition DISABLE_SESSION_ID_REUSE = new SimpleAttributeDefinitionBuilder(Constants.DISABLE_SESSION_ID_REUSE, ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(ModelNode.FALSE) .setAllowExpression(true) .build(); protected static final AttributeDefinition FILE_CACHE_METADATA_SIZE = new SimpleAttributeDefinitionBuilder(Constants.FILE_CACHE_METADATA_SIZE, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(new ModelNode(100)) .setAllowExpression(true) .build(); protected static final AttributeDefinition FILE_CACHE_MAX_FILE_SIZE = new SimpleAttributeDefinitionBuilder(Constants.FILE_CACHE_MAX_FILE_SIZE, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(new ModelNode(10 * 1024 * 1024)) .setAllowExpression(true) .build(); protected static final AttributeDefinition FILE_CACHE_TIME_TO_LIVE = new SimpleAttributeDefinitionBuilder(Constants.FILE_CACHE_TIME_TO_LIVE, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .build(); protected static final AttributeDefinition DEFAULT_COOKIE_VERSION = new SimpleAttributeDefinitionBuilder(Constants.DEFAULT_COOKIE_VERSION, ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.ZERO) .setValidator(new IntRangeValidator(0, 1, true,true)) .build(); protected static final AttributeDefinition PRESERVE_PATH_ON_FORWARD = new SimpleAttributeDefinitionBuilder("preserve-path-on-forward", ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); static final AttributeDefinition ORPHAN_SESSION_ALLOWED = new SimpleAttributeDefinitionBuilder("allow-orphan-session", ModelType.BOOLEAN) .setRequired(false) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); static final Collection<AttributeDefinition> ATTRIBUTES = List.of( ALLOW_NON_STANDARD_WRAPPERS, DEFAULT_BUFFER_CACHE, STACK_TRACE_ON_ERROR, DEFAULT_ENCODING, USE_LISTENER_ENCODING, IGNORE_FLUSH, EAGER_FILTER_INIT, DEFAULT_SESSION_TIMEOUT, DISABLE_CACHING_FOR_SECURED_PAGES, DIRECTORY_LISTING, PROACTIVE_AUTHENTICATION, SESSION_ID_LENGTH, MAX_SESSIONS, DISABLE_FILE_WATCH_SERVICE, DISABLE_SESSION_ID_REUSE, FILE_CACHE_METADATA_SIZE, FILE_CACHE_MAX_FILE_SIZE, FILE_CACHE_TIME_TO_LIVE, DEFAULT_COOKIE_VERSION, PRESERVE_PATH_ON_FORWARD, ORPHAN_SESSION_ALLOWED); ServletContainerDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKey())) .setAddHandler(new ServletContainerAdd()) .setRemoveHandler(ReloadRequiredRemoveStepHandler.INSTANCE) .addCapabilities(SERVLET_CONTAINER_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } @Override public List<? extends PersistentResourceDefinition> getChildren() { return List.of( new JspDefinition(), new AffinityCookieDefinition(), new SessionCookieDefinition(), new PersistentSessionsDefinition(), new WebsocketsDefinition(), new MimeMappingDefinition(), new WelcomeFileDefinition(), new CrawlerSessionManagementDefinition()); } }
12,489
47.789063
180
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpInvokerDefinition.java
/* * 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.CAPABILITY_HTTP_INVOKER_HOST; import static org.wildfly.extension.undertow.UndertowRootDefinition.HTTP_INVOKER_RUNTIME_CAPABILITY; import static org.wildfly.extension.undertow.logging.UndertowLogger.ROOT_LOGGER; import java.util.Arrays; import java.util.Collection; import java.util.function.Supplier; import io.undertow.server.handlers.PathHandler; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AttributeDefinition; 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.PathElement; 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.SimpleResourceDefinition; import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition; import org.jboss.as.controller.capability.DynamicNameMappers; 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.msc.service.ServiceName; import org.wildfly.security.auth.server.HttpAuthenticationFactory; /** * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class HttpInvokerDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.HTTP_INVOKER); static final RuntimeCapability<Void> HTTP_INVOKER_HOST_CAPABILITY = RuntimeCapability.Builder.of(CAPABILITY_HTTP_INVOKER_HOST, true, Void.class) .setDynamicNameMapper(DynamicNameMappers.PARENT) //.addDynamicRequirements(Capabilities.CAPABILITY_HOST) .addRequirements(Capabilities.CAPABILITY_HTTP_INVOKER) .build(); static final SimpleAttributeDefinition HTTP_AUTHENTICATION_FACTORY = new SimpleAttributeDefinitionBuilder(Constants.HTTP_AUTHENTICATION_FACTORY, ModelType.STRING, true) .setValidator(new StringLengthValidator(1, true)) .setRestartAllServices() .setCapabilityReference(Capabilities.REF_HTTP_AUTHENTICATION_FACTORY) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.AUTHENTICATION_FACTORY_REF) .setAlternatives(Constants.SECURITY_REALM) .build(); protected static final SimpleAttributeDefinition SECURITY_REALM = new SimpleAttributeDefinitionBuilder(Constants.SECURITY_REALM, ModelType.STRING, true) .setRestartAllServices() .setValidator(new StringLengthValidator(1, Integer.MAX_VALUE, true, false)) .addAccessConstraint(SensitiveTargetAccessConstraintDefinition.SECURITY_REALM_REF) .setAlternatives(Constants.HTTP_AUTHENTICATION_FACTORY) .setDeprecated(UndertowSubsystemModel.VERSION_12_0_0.getVersion()) .build(); protected static final SimpleAttributeDefinition PATH = new SimpleAttributeDefinitionBuilder(Constants.PATH, ModelType.STRING, true) .setValidator(new StringLengthValidator(1)) .setDefaultValue(new ModelNode("wildfly-services")) .setRestartAllServices() .build(); static final Collection<AttributeDefinition> ATTRIBUTES = Arrays.asList( // IMPORTANT -- keep these in xsd order as this order controls marshalling PATH, HTTP_AUTHENTICATION_FACTORY, SECURITY_REALM ); HttpInvokerDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getValue())) .setAddHandler(new HttpInvokerAdd()) .setRemoveHandler(new HttpInvokerRemove()) .setCapabilities(HTTP_INVOKER_HOST_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } private static final class HttpInvokerAdd extends AbstractAddStepHandler { HttpInvokerAdd() { super(ATTRIBUTES); } @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(); String path = PATH.resolveModelAttribute(context, model).asString(); String httpAuthenticationFactory = null; final ModelNode authFactory = HTTP_AUTHENTICATION_FACTORY.resolveModelAttribute(context, model); final ModelNode securityRealm = SECURITY_REALM.resolveModelAttribute(context, model); if (authFactory.isDefined()) { httpAuthenticationFactory = authFactory.asString(); } else if (securityRealm.isDefined()) { throw ROOT_LOGGER.runtimeSecurityRealmUnsupported(); } final String serverName = serverAddress.getLastElement().getValue(); final String hostName = hostAddress.getLastElement().getValue(); final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(HTTP_INVOKER_HOST_CAPABILITY); final Supplier<Host> hSupplier = sb.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverName, hostName); Supplier<HttpAuthenticationFactory> hafSupplier = null; final Supplier<PathHandler> phSupplier = sb.requiresCapability(HTTP_INVOKER_RUNTIME_CAPABILITY.getName(), PathHandler.class); if (httpAuthenticationFactory != null) { hafSupplier = sb.requiresCapability(Capabilities.REF_HTTP_AUTHENTICATION_FACTORY, HttpAuthenticationFactory.class, httpAuthenticationFactory); } sb.setInstance(new HttpInvokerHostService(hSupplier, hafSupplier, phSupplier, path)); sb.install(); } } private static final class HttpInvokerRemove extends ServiceRemoveStepHandler { HttpInvokerRemove() { super(new HttpInvokerAdd()); } @Override protected ServiceName serviceName(String name, PathAddress address) { return HTTP_INVOKER_HOST_CAPABILITY.getCapabilityServiceName(address); } } }
7,883
49.216561
172
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ImportedClassELResolver.java
/* * 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.common.Assert.checkNotNullParamWithNullPointerException; import jakarta.el.ELClass; import jakarta.el.ELContext; import jakarta.el.ELResolver; import jakarta.el.ImportHandler; import java.beans.FeatureDescriptor; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Iterator; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.security.manager.WildFlySecurityManager; /** * An {@link ELResolver} which supports resolution of EL expressions which use imported classes (for static field/method references) * * @author Jaikiran Pai * @see Section 1.5.3 of EL 3.0 spec */ public class ImportedClassELResolver extends ELResolver { private final Map<String, Object> cache = new ConcurrentHashMap<>(); private static final Object NULL_MARKER = new Object(); @Override public Object getValue(final ELContext context, final Object base, final Object property) { if (base != null) { return null; } if (!(property instanceof String)) { return null; } final ImportHandler importHandler = context.getImportHandler(); if (importHandler == null) { return null; } final String klassName = (String) property; Object cacheResult = cache.get(klassName); if(cacheResult != null) { if(cacheResult == NULL_MARKER) { return null; } else { context.setPropertyResolved(true); return new ELClass((Class) cacheResult); } } final Class<?> klass; if (WildFlySecurityManager.isChecking()) { klass = AccessController.doPrivileged(new PrivilegedAction<Class<?>>() { @Override public Class<?> run() { return importHandler.resolveClass(klassName); } }); } else { klass = importHandler.resolveClass(klassName); } if (klass != null) { cache.put(klassName, klass); context.setPropertyResolved(true); return new ELClass(klass); } else { cache.put(klassName, NULL_MARKER); } return null; } @Override public Class<?> getType(final ELContext context, final Object base, final Object property) { // we don't set any value on invocation of setValue of this resolver, so this getType method should just return // null and *not* mark the base, property combination as resolved return null; } @Override public void setValue(final ELContext context, final Object base, final Object property, final Object value) { Objects.requireNonNull(context, UndertowLogger.ROOT_LOGGER.nullNotAllowed("ELContext")); // we don't allow setting any value so this method } @Override public boolean isReadOnly(final ELContext context, final Object base, final Object property) { checkNotNullParamWithNullPointerException("context", context); // we don't allow setting any value via this resolver, so this is always read-only return true; } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(final ELContext context, final Object base) { return null; } @Override public Class<?> getCommonPropertyType(final ELContext context, final Object base) { return null; } }
4,673
35.515625
132
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/Capabilities.java
/* * 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_CONSOLE_ACCESS_LOG = "org.wildfly.undertow.host.console-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_HTTP_UPGRADE_REGISTRY = "org.wildfly.undertow.listener.http-upgrade-registry"; 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_LEGACY_SECURITY = "org.wildfly.legacy-security"; 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_HTTP_LISTENER_REGISTRY = "org.wildfly.remoting.http-listener-registry"; public static final String REF_OUTBOUND_SOCKET = "org.wildfly.network.outbound-socket-binding"; public static final String REF_REQUEST_CONTROLLER = "org.wildfly.request-controller"; public static final String REF_SUSPEND_CONTROLLER = "org.wildfly.server.suspend-controller"; }
4,147
60.910448
159
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ConsoleAccessLogDefinition.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.undertow; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Supplier; import io.undertow.predicate.Predicate; import io.undertow.predicate.Predicates; import org.jboss.as.controller.AbstractAddStepHandler; import org.jboss.as.controller.AbstractRemoveStepHandler; 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.PathElement; import org.jboss.as.controller.PersistentResourceDefinition; import org.jboss.as.controller.PropertiesAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.SimpleResourceDefinition; import org.jboss.as.controller.capability.DynamicNameMappers; import org.jboss.as.controller.capability.RuntimeCapability; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.dmr.Property; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController; import org.xnio.XnioWorker; /** * The resource definition for the {@code setting=console-access-log} resource. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class ConsoleAccessLogDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.CONSOLE_ACCESS_LOG); private static final RuntimeCapability<Void> CONSOLE_ACCESS_LOG_CAPABILITY = RuntimeCapability.Builder.of( Capabilities.CAPABILITY_CONSOLE_ACCESS_LOG, true, EventLoggerService.class) .setDynamicNameMapper(DynamicNameMappers.GRAND_PARENT) .build(); static final SimpleAttributeDefinition INCLUDE_HOST_NAME = SimpleAttributeDefinitionBuilder.create("include-host-name", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.TRUE) .setRestartAllServices() .build(); static final PropertiesAttributeDefinition METADATA = new PropertiesAttributeDefinition.Builder("metadata", true) .setAllowExpression(true) .setRestartAllServices() .build(); static final Collection<AttributeDefinition> ATTRIBUTES = Arrays.asList( ExchangeAttributeDefinitions.ATTRIBUTES, INCLUDE_HOST_NAME, AccessLogDefinition.WORKER, AccessLogDefinition.PREDICATE, METADATA ); ConsoleAccessLogDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getValue())) .setAddHandler(AddHandler.INSTANCE) .setRemoveHandler(RemoveHandler.INSTANCE) .addCapabilities(CONSOLE_ACCESS_LOG_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } private static class AddHandler extends AbstractAddStepHandler { static final AddHandler INSTANCE = new AddHandler(); private AddHandler() { super(ATTRIBUTES); } @Override protected void performRuntime(final OperationContext context, final ModelNode operation, final 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 ModelNode properties = METADATA.resolveModelAttribute(context, model); final Map<String, Object> metadata = new LinkedHashMap<>(); if (properties.isDefined()) { for (Property property : properties.asPropertyList()) { metadata.put(property.getName(), property.getValue().asString()); } } Predicate predicate = null; final ModelNode predicateNode = AccessLogDefinition.PREDICATE.resolveModelAttribute(context, model); if (predicateNode.isDefined()) { predicate = Predicates.parse(predicateNode.asString(), getClass().getClassLoader()); } final boolean includeHostName = INCLUDE_HOST_NAME.resolveModelAttribute(context, model).asBoolean(); final String serverName = serverAddress.getLastElement().getValue(); final String hostName = hostAddress.getLastElement().getValue(); final ServiceBuilder<?> serviceBuilder = context.getServiceTarget() .addService(CONSOLE_ACCESS_LOG_CAPABILITY.getCapabilityServiceName(address)); final Supplier<Host> hostSupplier = serviceBuilder.requires( context.getCapabilityServiceName(Capabilities.CAPABILITY_HOST, Host.class, serverName, hostName)); final Supplier<XnioWorker> workerSupplier = serviceBuilder.requires( context.getCapabilityServiceName(Capabilities.REF_IO_WORKER, XnioWorker.class, worker)); // Get the list of attributes to log final Collection<AccessLogAttribute> attributes = parseAttributes(context, model); final EventLoggerService service = new EventLoggerService(attributes, predicate, metadata, includeHostName, hostSupplier, workerSupplier); serviceBuilder.setInstance(service) .setInitialMode(ServiceController.Mode.ACTIVE) .install(); } private Collection<AccessLogAttribute> parseAttributes(final OperationContext context, final ModelNode model) throws OperationFailedException { final Collection<AccessLogAttribute> attributes = new ArrayList<>(); final ModelNode attributesModel = ExchangeAttributeDefinitions.ATTRIBUTES.resolveModelAttribute(context, model); for (AttributeDefinition valueType : ExchangeAttributeDefinitions.ATTRIBUTES.getValueTypes()) { attributes.addAll(ExchangeAttributeDefinitions.resolveAccessLogAttribute(valueType, context, attributesModel)); } return attributes; } } private static class RemoveHandler extends AbstractRemoveStepHandler { static final RemoveHandler INSTANCE = new RemoveHandler(); @Override protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { final PathAddress address = context.getCurrentAddress(); context.removeService(CONSOLE_ACCESS_LOG_CAPABILITY.getCapabilityServiceName(address)); } @Override protected void recoverServices(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { AddHandler.INSTANCE.performRuntime(context, operation, model); } } }
7,900
45.751479
154
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/LocationService.java
/* * 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 org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.undertow.logging.UndertowLogger; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import java.util.function.Supplier; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public final class LocationService implements Service<LocationService>, FilterLocation { private final Consumer<LocationService> serviceConsumer; private final Supplier<HttpHandler> httpHandler; private final Supplier<Host> host; private final String locationPath; private final CopyOnWriteArrayList<UndertowFilter> filters = new CopyOnWriteArrayList<>(); private final LocationHandler locationHandler = new LocationHandler(); private volatile HttpHandler configuredHandler; LocationService(final Consumer<LocationService> serviceConsumer, final Supplier<HttpHandler> httpHandler, final Supplier<Host> host, String locationPath) { this.serviceConsumer = serviceConsumer; this.httpHandler = httpHandler; this.host = host; this.locationPath = locationPath; } @Override public void start(final StartContext context) { UndertowLogger.ROOT_LOGGER.tracef("registering handler %s under path '%s'", httpHandler.get(), locationPath); host.get().registerLocation(this); serviceConsumer.accept(this); } @Override public void stop(final StopContext context) { serviceConsumer.accept(null); host.get().unregisterLocation(this); } @Override public LocationService getValue() throws IllegalStateException, IllegalArgumentException { return this; } String getLocationPath() { return locationPath; } LocationHandler getLocationHandler() { return locationHandler; } private HttpHandler configureHandler() { ArrayList<UndertowFilter> filters = new ArrayList<>(this.filters); return configureHandlerChain(httpHandler.get(), filters); } protected static HttpHandler configureHandlerChain(HttpHandler rootHandler, List<UndertowFilter> filters) { filters.sort((o1, o2) -> Integer.compare(o1.getPriority(), o2.getPriority())); Collections.reverse(filters); //handler chain goes last first HttpHandler handler = rootHandler; for (UndertowFilter filter : filters) { handler = filter.wrap(handler); } return handler; } @Override public void addFilter(UndertowFilter filterRef) { filters.add(filterRef); configuredHandler = null; } @Override public void removeFilter(UndertowFilter filterRef) { filters.remove(filterRef); configuredHandler = null; } private class LocationHandler implements HttpHandler { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { HttpHandler root = configuredHandler; if(root == null) { synchronized (LocationService.this) { root = configuredHandler; if(root == null) { root = configuredHandler = configureHandler(); } } } root.handleRequest(exchange); } } }
4,771
34.61194
117
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ServletContainerService.java
/* * 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.connector.ByteBufferPool; import io.undertow.server.handlers.cache.DirectBufferCache; import io.undertow.servlet.api.CrawlerSessionManagerConfig; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.api.ServletStackTraces; import io.undertow.servlet.api.SessionPersistenceManager; import org.xnio.XnioWorker; import java.util.List; import java.util.Map; /** * Central Undertow 'Container' HTTP listeners will make this container accessible whilst deployers will add content. * * @author <a href="mailto:[email protected]">Darran Lofthouse</a> * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public interface ServletContainerService { ServletContainer getServletContainer(); boolean isAllowNonStandardWrappers(); JSPConfig getJspConfig(); ServletStackTraces getStackTraces(); CookieConfig getSessionCookieConfig(); CookieConfig getAffinityCookieConfig(); DirectBufferCache getBufferCache(); boolean isDisableCachingForSecuredPages(); boolean isDispatchWebsocketInvocationToWorker(); boolean isPerMessageDeflate(); int getDeflaterLevel(); boolean isWebsocketsEnabled(); boolean isDisableSessionIdReuse(); SessionPersistenceManager getSessionPersistenceManager(); XnioWorker getWebsocketsWorker(); ByteBufferPool getWebsocketsBufferPool(); String getDefaultEncoding(); boolean isUseListenerEncoding(); boolean isIgnoreFlush(); boolean isEagerFilterInit(); int getDefaultSessionTimeout(); Map<String, String> getMimeMappings(); List<String> getWelcomeFiles(); Boolean getDirectoryListingEnabled(); boolean isProactiveAuth(); int getSessionIdLength(); Integer getMaxSessions(); boolean isDisableFileWatchService(); CrawlerSessionManagerConfig getCrawlerSessionManagerConfig(); int getFileCacheMetadataSize(); int getFileCacheMaxFileSize(); Integer getFileCacheTimeToLive(); int getDefaultCookieVersion(); boolean isPreservePathOnForward(); boolean isOrphanSessionAllowed(); }
3,190
26.747826
117
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/SessionCookieDefinition.java
/* * JBoss, Home of Professional Open Source. * Copyright 2023, 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.EnumSet; import java.util.stream.Collectors; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathElement; import org.jboss.dmr.ModelNode; /** * Resource description for the session cookie configuration. * * @author Radoslav Husar */ class SessionCookieDefinition extends AbstractCookieDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.SESSION_COOKIE); static final Collection<AttributeDefinition> ATTRIBUTES = EnumSet.complementOf(EnumSet.of(Attribute.REQUIRED_NAME)) .stream().map(Attribute::getDefinition).collect(Collectors.toUnmodifiableSet()); SessionCookieDefinition() { super(PATH_ELEMENT, ATTRIBUTES); } static CookieConfig getConfig(final ExpressionResolver context, final ModelNode model) throws OperationFailedException { return AbstractCookieDefinition.getConfig(Attribute.OPTIONAL_NAME, context, model); } }
2,193
38.890909
124
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowService.java
/* * 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.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.function.Consumer; import org.jboss.as.controller.PathAddress; 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.wildfly.extension.undertow.logging.UndertowLogger; import io.undertow.Version; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ @SuppressWarnings("ALL") public class UndertowService implements Service<UndertowService> { /** * @deprecated Replaced by capability reference {@link UndertowRootDefinition#UNDERTOW_CAPABILITY}. */ @Deprecated public static final ServiceName UNDERTOW = ServiceName.JBOSS.append("undertow"); /** * @deprecated Replaced by capability reference {@link ServletContainerDefinition#SERVLET_CONTAINER_CAPABILITY}. */ @Deprecated public static final ServiceName SERVLET_CONTAINER = UNDERTOW.append(Constants.SERVLET_CONTAINER); /** * @deprecated Replaced by capability reference {@link HostDefinition.HOST_CAPABILITY}. */ @Deprecated public static final ServiceName SERVER = UNDERTOW.append(Constants.SERVER); /** * service name under which default server is bound. */ public static final ServiceName DEFAULT_SERVER = UNDERTOW.append("default-server"); /** * service name under which default host of default server is bound. */ public static final ServiceName DEFAULT_HOST = DEFAULT_SERVER.append("default-host"); public static final ServiceName UNDERTOW_DEPLOYMENT = ServiceName.of("undertow-deployment"); /** * The base name for listener/handler/filter services. */ public static final ServiceName HANDLER = UNDERTOW.append(Constants.HANDLER); public static final ServiceName FILTER = UNDERTOW.append(Constants.FILTER); /** * The base name for web deployments. */ static final ServiceName WEB_DEPLOYMENT_BASE = UNDERTOW.append("deployment"); private final String defaultContainer; private final String defaultServer; private final String defaultVirtualHost; private final Set<Server> registeredServers = new CopyOnWriteArraySet<>(); private final List<UndertowEventListener> listeners = Collections.synchronizedList(new LinkedList<UndertowEventListener>()); private final String instanceId; private final boolean obfuscateSessionRoute; private volatile boolean statisticsEnabled; private final Set<Consumer<Boolean>> statisticsChangeListenters = new HashSet<>(); private final Consumer<UndertowService> serviceConsumer; protected UndertowService(final Consumer<UndertowService> serviceConsumer, final String defaultContainer, final String defaultServer, final String defaultVirtualHost, final String instanceId, final boolean obfuscateSessionRoute, final boolean statisticsEnabled) { this.serviceConsumer = serviceConsumer; this.defaultContainer = defaultContainer; this.defaultServer = defaultServer; this.defaultVirtualHost = defaultVirtualHost; this.instanceId = instanceId; this.obfuscateSessionRoute = obfuscateSessionRoute; this.statisticsEnabled = statisticsEnabled; } public static ServiceName deploymentServiceName(ServiceName deploymentServiceName) { return deploymentServiceName.append(UNDERTOW_DEPLOYMENT); } /** * The old deployment unit service name. This is still registered as an alias, however {{@link #deploymentServiceName(ServiceName)}} * should be used instead. * @param serverName The server name * @param virtualHost The virtual host * @param contextPath The context path * @return The legacy deployment service alias */ @Deprecated public static ServiceName deploymentServiceName(final String serverName, final String virtualHost, final String contextPath) { return WEB_DEPLOYMENT_BASE.append(serverName).append(virtualHost).append("".equals(contextPath) ? "/" : contextPath); } @Deprecated public static ServiceName virtualHostName(final String server, final String virtualHost) { return SERVER.append(server).append(virtualHost); } public static ServiceName locationServiceName(final String server, final String virtualHost, final String locationName) { return virtualHostName(server, virtualHost).append(Constants.LOCATION, locationName); } public static ServiceName accessLogServiceName(final String server, final String virtualHost) { return virtualHostName(server, virtualHost).append(Constants.ACCESS_LOG); } public static ServiceName consoleRedirectServiceName(final String server, final String virtualHost) { return virtualHostName(server, virtualHost).append("console", "redirect"); } public static ServiceName filterRefName(final String server, final String virtualHost, final String locationName, final String filterName) { return virtualHostName(server, virtualHost).append(Constants.LOCATION, locationName).append("filter-ref").append(filterName); } public static ServiceName filterRefName(final String server, final String virtualHost, final String filterName) { return SERVER.append(server).append(virtualHost).append("filter-ref").append(filterName); } public static ServiceName getFilterRefServiceName(final PathAddress address, String name) { final PathAddress oneUp = address.subAddress(0, address.size() - 1); final PathAddress twoUp = oneUp.subAddress(0, oneUp.size() - 1); final PathAddress threeUp = twoUp.subAddress(0, twoUp.size() - 1); ServiceName serviceName; if (address.getLastElement().getKey().equals(Constants.FILTER_REF)) { if (oneUp.getLastElement().getKey().equals(Constants.HOST)) { //adding reference String host = oneUp.getLastElement().getValue(); String server = twoUp.getLastElement().getValue(); serviceName = UndertowService.filterRefName(server, host, name); } else { String location = oneUp.getLastElement().getValue(); String host = twoUp.getLastElement().getValue(); String server = threeUp.getLastElement().getValue(); serviceName = UndertowService.filterRefName(server, host, location, name); } } else if (address.getLastElement().getKey().equals(Constants.HOST)) { String host = address.getLastElement().getValue(); String server = oneUp.getLastElement().getValue(); serviceName = UndertowService.filterRefName(server, host, name); } else { String location = address.getLastElement().getValue(); String host = oneUp.getLastElement().getValue(); String server = twoUp.getLastElement().getValue(); serviceName = UndertowService.filterRefName(server, host, location, name); } return serviceName; } @Deprecated public static ServiceName listenerName(String listenerName) { return UNDERTOW.append(Constants.LISTENER).append(listenerName); } @Override public void start(final StartContext context) throws StartException { UndertowLogger.ROOT_LOGGER.serverStarting(Version.getVersionString()); serviceConsumer.accept(this); } @Override public void stop(final StopContext context) { serviceConsumer.accept(null); UndertowLogger.ROOT_LOGGER.serverStopping(Version.getVersionString()); fireEvent(new EventInvoker() { @Override public void invoke(UndertowEventListener listener) { listener.onShutdown(); } }); } @Override public UndertowService getValue() throws IllegalStateException, IllegalArgumentException { return this; } protected void registerServer(final Server server) { registeredServers.add(server); fireEvent(new EventInvoker() { @Override public void invoke(UndertowEventListener listener) { listener.onServerStart(server); } }); } protected void unregisterServer(final Server server) { registeredServers.remove(server); fireEvent(new EventInvoker() { @Override public void invoke(UndertowEventListener listener) { listener.onServerStop(server); } }); } public String getDefaultContainer() { return defaultContainer; } public String getDefaultServer() { return defaultServer; } public String getDefaultVirtualHost() { return defaultVirtualHost; } public Set<Server> getServers() { return Collections.unmodifiableSet(registeredServers); } public String getInstanceId() { return instanceId; } public boolean isObfuscateSessionRoute() { return obfuscateSessionRoute; } public boolean isStatisticsEnabled() { return statisticsEnabled; } public synchronized void setStatisticsEnabled(boolean statisticsEnabled) { this.statisticsEnabled = statisticsEnabled; for(Consumer<Boolean> listener: statisticsChangeListenters) { listener.accept(statisticsEnabled); } } public synchronized void registerStatisticsListener(Consumer<Boolean> listener) { statisticsChangeListenters.add(listener); } public synchronized void unregisterStatisticsListener(Consumer<Boolean> listener) { statisticsChangeListenters.remove(listener); } /** * Registers custom Event listener to server * * @param listener event listener to register */ public void registerListener(UndertowEventListener listener) { this.listeners.add(listener); } public void unregisterListener(UndertowEventListener listener) { this.listeners.remove(listener); } protected void fireEvent(EventInvoker invoker) { synchronized (listeners) { for (UndertowEventListener listener : listeners) { invoker.invoke(listener); } } } }
11,727
38.488215
144
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/WebsocketsDefinition.java
/* * 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.CAPABILITY_BYTE_BUFFER_POOL; import static org.wildfly.extension.undertow.Capabilities.REF_IO_WORKER; 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.ExpressionResolver; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; 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.SimpleResourceDefinition; import org.jboss.as.controller.capability.RuntimeCapability; 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.jboss.msc.service.ServiceName; /** * Global websocket configuration * * @author Stuart Douglas */ class WebsocketsDefinition extends PersistentResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.SETTING, Constants.WEBSOCKETS); private static final RuntimeCapability<Void> WEBSOCKET_CAPABILITY = RuntimeCapability.Builder.of(Capabilities.CAPABILITY_WEBSOCKET, true, UndertowListener.class) .setDynamicNameMapper(pathElements -> new String[]{ pathElements.getParent().getLastElement().getValue() }) .build(); protected static final SimpleAttributeDefinition BUFFER_POOL = new SimpleAttributeDefinitionBuilder("buffer-pool", ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(new ModelNode("default")) .setCapabilityReference(CAPABILITY_BYTE_BUFFER_POOL) .build(); protected static final SimpleAttributeDefinition WORKER = new SimpleAttributeDefinitionBuilder("worker", ModelType.STRING, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setDefaultValue(new ModelNode("default")) .setCapabilityReference(REF_IO_WORKER) .build(); protected static final SimpleAttributeDefinition DISPATCH_TO_WORKER = new SimpleAttributeDefinitionBuilder("dispatch-to-worker", ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.TRUE) .build(); protected static final SimpleAttributeDefinition PER_MESSAGE_DEFLATE = new SimpleAttributeDefinitionBuilder("per-message-deflate", ModelType.BOOLEAN, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); protected static final SimpleAttributeDefinition DEFLATER_LEVEL = new SimpleAttributeDefinitionBuilder("deflater-level", ModelType.INT, true) .setFlags(AttributeAccess.Flag.RESTART_ALL_SERVICES) .setAllowExpression(true) .setValidator(new IntRangeValidator(0, 9, true, true)) .setDefaultValue(ModelNode.ZERO) .build(); protected static final List<AttributeDefinition> ATTRIBUTES = Arrays.asList( BUFFER_POOL, WORKER, DISPATCH_TO_WORKER, PER_MESSAGE_DEFLATE, DEFLATER_LEVEL ); WebsocketsDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(PATH_ELEMENT.getKeyValuePair())) .setAddHandler(new WebsocketsAdd()) .setRemoveHandler(new WebsocketsRemove()) .addCapabilities(WEBSOCKET_CAPABILITY) ); } @Override public Collection<AttributeDefinition> getAttributes() { return ATTRIBUTES; } static WebSocketInfo getConfig(final ExpressionResolver context, final ModelNode model) throws OperationFailedException { if (!model.isDefined()) { return null; } boolean dispatchToWorker = DISPATCH_TO_WORKER.resolveModelAttribute(context, model).asBoolean(); String bufferPool = BUFFER_POOL.resolveModelAttribute(context, model).asString(); String worker = WORKER.resolveModelAttribute(context, model).asString(); boolean perMessageDeflate = PER_MESSAGE_DEFLATE.resolveModelAttribute(context, model).asBoolean(); int deflaterLevel = DEFLATER_LEVEL.resolveModelAttribute(context, model).asInt(); return new WebSocketInfo(worker, bufferPool, dispatchToWorker, perMessageDeflate, deflaterLevel); } private static class WebsocketsAdd extends RestartParentResourceAddHandler { protected WebsocketsAdd() { super(ServletContainerDefinition.PATH_ELEMENT.getKey(), Collections.singleton(WEBSOCKET_CAPABILITY), ATTRIBUTES); } @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.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY.getCapabilityServiceName(parentAddress); } } private static class WebsocketsRemove extends RestartParentResourceRemoveHandler { protected WebsocketsRemove() { super(ServletContainerDefinition.PATH_ELEMENT.getKey()); } @Override protected void recreateParentService(OperationContext context, PathAddress parentAddress, ModelNode parentModel) throws OperationFailedException { ServletContainerAdd.installRuntimeServices(context.getCapabilityServiceTarget(), context, parentAddress, parentModel); } @Override protected ServiceName getParentServiceName(PathAddress parentAddress) { return ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY.getCapabilityServiceName(parentAddress); } } public static class WebSocketInfo { private final String worker; private final String bufferPool; private final boolean dispatchToWorker; private final boolean perMessageDeflate; private final int deflaterLevel; public WebSocketInfo(String worker, String bufferPool, boolean dispatchToWorker, boolean perMessageDeflate, int deflaterLevel) { this.worker = worker; this.bufferPool = bufferPool; this.dispatchToWorker = dispatchToWorker; this.perMessageDeflate = perMessageDeflate; this.deflaterLevel = deflaterLevel; } public String getWorker() { return worker; } public String getBufferPool() { return bufferPool; } public boolean isDispatchToWorker() { return dispatchToWorker; } public boolean isPerMessageDeflate() { return perMessageDeflate; } public int getDeflaterLevel() { return deflaterLevel; } } }
9,209
42.239437
165
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AjpListenerService.java
/* * 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 java.util.function.Consumer; import io.undertow.UndertowOptions; import io.undertow.server.OpenListener; import io.undertow.server.protocol.ajp.AjpOpenListener; import org.jboss.as.controller.PathAddress; 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 <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class AjpListenerService extends ListenerService { private volatile AcceptingChannel<StreamConnection> server; private final String scheme; private final PathAddress address; public AjpListenerService(Consumer<ListenerService> serviceConsumer, final PathAddress address, final String scheme, OptionMap listenerOptions, OptionMap socketOptions) { super(serviceConsumer, address.getLastElement().getValue(), listenerOptions, socketOptions, false); this.address = address; this.scheme = scheme; } @Override protected OpenListener createOpenListener() { AjpOpenListener ajpOpenListener = new AjpOpenListener(getBufferPool().get(), 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<AcceptingChannel<StreamConnection>> 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"; } }
4,353
38.944954
254
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/Host.java
/* * 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.QUEUE_REQUESTS_ON_START; 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 java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.regex.Pattern; 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.wildfly.extension.undertow.deployment.GateHandlerWrapper; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.security.manager.WildFlySecurityManager; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author Radoslav Husar * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class Host implements Service<Host>, FilterLocation { private final Consumer<Host> serviceConsumer; private final Supplier<Server> server; private final Supplier<UndertowService> undertowService; private final Supplier<ControlledProcessStateService> controlledProcessStateService; private final Supplier<SuspendController> suspendController; private final PathHandler pathHandler = new PathHandler(); private final Set<String> allAliases; private final String name; private final String defaultWebModule; private final List<UndertowFilter> filters = new CopyOnWriteArrayList<>(); private final Set<Deployment> deployments = new CopyOnWriteArraySet<>(); private final Map<String, LocationService> locations = new CopyOnWriteMap<>(); private final Map<String, AuthenticationMechanism> additionalAuthenticationMechanisms = new ConcurrentHashMap<>(); private final HostRootHandler hostRootHandler = new HostRootHandler(); private final DefaultResponseCodeHandler defaultHandler; private final Boolean queueRequestsOnStart; private final int defaultResponseCode; private volatile HttpHandler rootHandler = null; private volatile AccessLogService accessLogService; private volatile GateHandlerWrapper gateHandlerWrapper; private volatile Function<HttpHandler, HttpHandler> accessLogHttpHandler; 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 Consumer<Host> serviceConsumer, final Supplier<Server> server, final Supplier<UndertowService> undertowService, final Supplier<ControlledProcessStateService> controlledProcessStateService, final Supplier<SuspendController> suspendController, final String name, final List<String> aliases, final String defaultWebModule, final int defaultResponseCode, final Boolean queueRequestsOnStart ) { this.serviceConsumer = serviceConsumer; this.server = server; this.undertowService = undertowService; this.controlledProcessStateService = controlledProcessStateService; this.suspendController = suspendController; this.name = name; this.defaultWebModule = defaultWebModule; Set<String> 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 { suspendController.get().registerActivity(suspendListener); SuspendController.State state = suspendController.get().getState(); if(state == SuspendController.State.RUNNING) { defaultHandler.setSuspended(false); } else { defaultHandler.setSuspended(true); } ControlledProcessStateService controlledProcessStateService = this.controlledProcessStateService.get(); //may be null for tests if(controlledProcessStateService != null && controlledProcessStateService.getCurrentState() == ControlledProcessState.State.STARTING) { // Non-graceful is ControlledProcessState.State.STARTING && SuspendController.State.RUNNING. We know from above // that we are STARTING, so we just need to check that state of the SuspendController boolean nonGraceful = state == SuspendController.State.RUNNING; int statusCode = defaultResponseCode; if (nonGraceful && queueRequestsOnStart == null) { UndertowLogger.ROOT_LOGGER.debug("Running in non-graceful mode and " + QUEUE_REQUESTS_ON_START.getName() + " not explicitly set. Requests will not be queued."); } else { if (queueRequestsOnStart == null || Boolean.TRUE.equals(queueRequestsOnStart)) { UndertowLogger.ROOT_LOGGER.info("Queuing requests."); statusCode = -1; } gateHandlerWrapper = new GateHandlerWrapper(statusCode); controlledProcessStateService.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { controlledProcessStateService.removePropertyChangeListener(this); if (gateHandlerWrapper != null) { gateHandlerWrapper.open(); gateHandlerWrapper = null; } rootHandler = null; } }); } } server.get().registerHost(this); UndertowLogger.ROOT_LOGGER.hostStarting(name); serviceConsumer.accept(this); } private HttpHandler configureRootHandler() { AccessLogService logService = accessLogService; HttpHandler rootHandler = pathHandler; final Function<HttpHandler, HttpHandler> accessLogHttpHandler = this.accessLogHttpHandler; ArrayList<UndertowFilter> 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); } if (accessLogHttpHandler != null) { rootHandler = accessLogHttpHandler.apply(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(final StopContext context) { serviceConsumer.accept(null); server.get().unregisterHost(this); pathHandler.clearPaths(); if(gateHandlerWrapper != null) { gateHandlerWrapper.open(); gateHandlerWrapper = null; } UndertowLogger.ROOT_LOGGER.hostStopping(name); suspendController.get().unRegisterActivity(suspendListener); } @Override public Host getValue() throws IllegalStateException, IllegalArgumentException { return this; } void setAccessLogService(AccessLogService service) { this.accessLogService = service; rootHandler = null; } void setAccessLogHandler(final Function<HttpHandler, HttpHandler> accessLogHttpHandler) { this.accessLogHttpHandler = accessLogHttpHandler; rootHandler = null; } public Server getServer() { return server.get(); } public Set<String> getAllAliases() { return allAliases; } public String getName() { return name; } protected HttpHandler getRootHandler() { return hostRootHandler; } List<UndertowFilter> 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.get().fireEvent(listener -> listener.onDeploymentStart(deployment, Host.this)); } public void unregisterDeployment(final Deployment deployment) { DeploymentInfo deploymentInfo = deployment.getDeploymentInfo(); String path = getDeployedContextPath(deploymentInfo); undertowService.get().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.get().fireEvent(listener -> listener.onDeploymentStart(realPath, Host.this)); } void unregisterLocation(String path) { String realPath = path.startsWith("/") ? path : "/" + path; locations.remove(realPath); undertowService.get().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.get().fireEvent(listener -> listener.onDeploymentStart(location.getLocationPath(), Host.this)); } void unregisterLocation(LocationService location) { locations.remove(location.getLocationPath()); unregisterHandler(location.getLocationPath()); undertowService.get().fireEvent(listener -> listener.onDeploymentStop(location.getLocationPath(), Host.this)); } public Set<String> getLocations() { return Collections.unmodifiableSet(locations.keySet()); } /** * @return set of currently registered {@link Deployment}s on this host */ public Set<Deployment> getDeployments() { return Collections.unmodifiableSet(deployments); } void registerAdditionalAuthenticationMechanism(String name, AuthenticationMechanism authenticationMechanism){ additionalAuthenticationMechanisms.put(name, authenticationMechanism); } void unregisterAdditionalAuthenticationMechanism(String name){ additionalAuthenticationMechanisms.remove(name); } public Map<String, AuthenticationMechanism> getAdditionalAuthenticationMechanisms() { return new LinkedHashMap<>(additionalAuthenticationMechanisms); } @Override public void addFilter(UndertowFilter filterRef) { filters.add(filterRef); rootHandler = null; } @Override public void removeFilter(UndertowFilter filterRef) { filters.remove(filterRef); rootHandler = null; } public SuspendController.State getSuspendState() { return this.suspendController.get().getState(); } protected void setupDefaultResponseCodeHandler(){ if(this.defaultHandler != null){ this.registerHandler("/", this.defaultHandler); } } 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_CONTEXT = "/.well-known/acme-challenge/"; private static final Pattern ACME_CHALLENGE_PATTERN = Pattern.compile("/\\.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().startsWith(ACME_CHALLENGE_CONTEXT, 0) && ACME_CHALLENGE_PATTERN.matcher(exchange.getRelativePath()).matches()) { super.handleRequest(exchange); } else { next.handleRequest(exchange); } } } private class HostRootHandler implements HttpHandler { @Override public void handleRequest(HttpServerExchange exchange) throws Exception { getOrCreateRootHandler().handleRequest(exchange); } } }
18,246
39.729911
159
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AjpListenerResourceDefinition.java
/* * 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 java.util.Map; import io.undertow.UndertowOptions; import io.undertow.protocols.ajp.AjpClientRequestClientStreamSinkChannel; import org.jboss.as.controller.AttributeDefinition; 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.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 <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. */ public class AjpListenerResourceDefinition extends ListenerResourceDefinition { static final PathElement PATH_ELEMENT = PathElement.pathElement(Constants.AJP_LISTENER); 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(); static final List<AttributeDefinition> ATTRIBUTES = List.of(SCHEME, REDIRECT_SOCKET, MAX_AJP_PACKET_SIZE); AjpListenerResourceDefinition() { super(new SimpleResourceDefinition.Parameters(PATH_ELEMENT, UndertowExtension.getResolver(Constants.LISTENER)), AjpListenerAdd::new, Map.of()); } @Override public Collection<AttributeDefinition> getAttributes() { List<AttributeDefinition> attributes = new ArrayList<>(ListenerResourceDefinition.ATTRIBUTES.size() + ATTRIBUTES.size()); attributes.addAll(ListenerResourceDefinition.ATTRIBUTES); attributes.addAll(ATTRIBUTES); return attributes; } }
3,574
44.253165
151
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AccessLogRemove.java
/* * 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 <a href="mailto:[email protected]">Tomaz Cerar</a> (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); } }
2,356
43.471698
132
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpInvokerHostService.java
/* * 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.List; import java.util.function.Supplier; import java.util.stream.Collectors; import io.undertow.security.handlers.AuthenticationCallHandler; import io.undertow.security.handlers.AuthenticationConstraintHandler; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.Cookie; import io.undertow.server.handlers.CookieImpl; import io.undertow.server.handlers.PathHandler; import io.undertow.server.session.SecureRandomSessionIdGenerator; import io.undertow.util.StatusCodes; import org.jboss.as.web.session.SimpleRoutingSupport; import org.jboss.as.web.session.SimpleSessionIdentifierCodec; import org.jboss.msc.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.elytron.web.undertow.server.ElytronContextAssociationHandler; import org.wildfly.elytron.web.undertow.server.ElytronHttpExchange; import org.wildfly.httpclient.common.ElytronIdentityHandler; import org.wildfly.security.auth.server.HttpAuthenticationFactory; import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.http.HttpServerAuthenticationMechanism; /** * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class HttpInvokerHostService implements Service { private static final String JSESSIONID = "JSESSIONID"; private final Supplier<Host> host; private final Supplier<HttpAuthenticationFactory> httpAuthenticationFactory; private final Supplier<PathHandler> remoteHttpInvokerService; private final String path; HttpInvokerHostService( final Supplier<Host> host, final Supplier<HttpAuthenticationFactory> httpAuthenticationFactory, final Supplier<PathHandler> remoteHttpInvokerService, final String path) { this.host = host; this.httpAuthenticationFactory = httpAuthenticationFactory; this.remoteHttpInvokerService = remoteHttpInvokerService; this.path = path; } @Override public void start(final StartContext startContext) { HttpHandler handler = remoteHttpInvokerService.get(); if (httpAuthenticationFactory != null) { handler = secureAccess(handler, httpAuthenticationFactory.get()); } handler = setupRoutes(handler); host.get().registerHandler(path, handler); host.get().registerLocation(path); } @Override public void stop(final StopContext stopContext) { host.get().unregisterHandler(path); host.get().unregisterLocation(path); } private HttpHandler setupRoutes(HttpHandler handler) { final SimpleSessionIdentifierCodec codec = new SimpleSessionIdentifierCodec(new SimpleRoutingSupport(), this.host.get().getServer().getRoute()); final SecureRandomSessionIdGenerator generator = new SecureRandomSessionIdGenerator(); return exchange -> { exchange.addResponseCommitListener(ex -> { Cookie cookie = ex.getResponseCookies().get(JSESSIONID); if (cookie != null ) { cookie.setValue(codec.encode(cookie.getValue()).toString()); } else if (ex.getStatusCode() == StatusCodes.UNAUTHORIZED) { // add a session cookie in order to avoid sticky session issue after 401 Unauthorized response cookie = new CookieImpl("JSESSIONID", codec.encode(generator.createSessionId()).toString()); cookie.setPath(ex.getResolvedPath()); exchange.getResponseCookies().put("JSESSIONID", cookie); } }); handler.handleRequest(exchange); }; } private static HttpHandler secureAccess(HttpHandler domainHandler, final HttpAuthenticationFactory httpAuthenticationFactory) { domainHandler = new AuthenticationCallHandler(domainHandler); domainHandler = new AuthenticationConstraintHandler(domainHandler); Supplier<List<HttpServerAuthenticationMechanism>> mechanismSupplier = () -> httpAuthenticationFactory.getMechanismNames().stream() .map(s -> { try { return httpAuthenticationFactory.createMechanism(s); } catch (Exception e) { return null; } }) .collect(Collectors.toList()); domainHandler = ElytronContextAssociationHandler.builder() .setNext(domainHandler) .setMechanismSupplier(mechanismSupplier) .setHttpExchangeSupplier(h -> new ElytronHttpExchange(h) { @Override public void authenticationComplete(SecurityIdentity securityIdentity, String mechanismName) { super.authenticationComplete(securityIdentity, mechanismName); h.putAttachment(ElytronIdentityHandler.IDENTITY_KEY, securityIdentity); } }) .build(); return domainHandler; } public String getPath() { return path; } }
6,310
43.132867
152
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/PredicateValidator.java
/* * 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.OperationFailedException; import org.jboss.as.controller.operations.validation.ModelTypeValidator; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.wildfly.extension.undertow.logging.UndertowLogger; import io.undertow.predicate.PredicateParser; /** * @author Stuart Douglas */ public class PredicateValidator extends ModelTypeValidator { public static final PredicateValidator INSTANCE = new PredicateValidator(); private PredicateValidator() { super(ModelType.STRING, true, true); } /** * {@inheritDoc} */ @Override public void validateParameter(String parameterName, ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); if (value.isDefined() && value.getType() != ModelType.EXPRESSION) { String val = value.asString(); try { PredicateParser.parse(val, getClass().getClassLoader()); } catch (Exception e) { throw new OperationFailedException(UndertowLogger.ROOT_LOGGER.predicateNotValid(val, e.getMessage()), e); } } } }
2,245
37.067797
121
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/Handler.java
/* * 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<AttributeDefinition> getAttributes(); Class<? extends HttpHandler> getHandlerClass(); HttpHandler createHttpHandler(final Predicate predicate, final ModelNode model, final HttpHandler next); }
1,558
35.255814
108
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowExtension.java
/* * 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.EnumSet; import java.util.List; import org.jboss.as.controller.Extension; import org.jboss.as.controller.ExtensionContext; import org.jboss.as.controller.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentResourceXMLDescriptionReader; import org.jboss.as.controller.PersistentResourceXMLDescriptionWriter; import org.jboss.as.controller.SubsystemRegistration; import org.jboss.as.controller.descriptions.StandardResourceDescriptionResolver; import org.jboss.as.controller.operations.common.GenericSubsystemDescribeHandler; import org.jboss.as.controller.parsing.ExtensionParsingContext; import org.jboss.as.controller.registry.ManagementResourceRegistration; import org.jboss.dmr.ModelNode; import org.jboss.staxmapper.XMLElementReader; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. */ public class UndertowExtension implements Extension { public static final String SUBSYSTEM_NAME = "undertow"; private static final String RESOURCE_NAME = UndertowExtension.class.getPackage().getName() + ".LocalDescriptions"; public static StandardResourceDescriptionResolver getResolver(final String... keyPrefix) { StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME); for (String kp : keyPrefix) { prefix.append('.').append(kp); } return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, UndertowExtension.class.getClassLoader(), true, false); } private final PersistentResourceXMLDescription currentDescription = UndertowSubsystemSchema.CURRENT.getXMLDescription(); @Override public void initializeParsers(ExtensionParsingContext context) { for (UndertowSubsystemSchema schema : EnumSet.allOf(UndertowSubsystemSchema.class)) { XMLElementReader<List<ModelNode>> reader = (schema == UndertowSubsystemSchema.CURRENT) ? new PersistentResourceXMLDescriptionReader(this.currentDescription) : schema; context.setSubsystemXmlMapping(SUBSYSTEM_NAME, schema.getNamespace().getUri(), reader); } } @Override public void initialize(ExtensionContext context) { final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, UndertowSubsystemModel.CURRENT.getVersion()); final ManagementResourceRegistration registration = subsystem.registerSubsystemModel(new UndertowRootDefinition()); registration.registerOperationHandler(GenericSubsystemDescribeHandler.DEFINITION, GenericSubsystemDescribeHandler.INSTANCE, false); final ManagementResourceRegistration deployments = subsystem.registerDeploymentModel(new DeploymentDefinition()); deployments.registerSubModel(new DeploymentServletDefinition()); deployments.registerSubModel(new DeploymentWebSocketDefinition()); subsystem.registerXMLElementWriter(new PersistentResourceXMLDescriptionWriter(this.currentDescription)); } }
4,043
48.925926
178
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/EventLoggerHttpHandler.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.undertow; import java.util.Collection; import java.util.LinkedHashMap; import java.util.Map; import io.undertow.predicate.Predicate; import io.undertow.server.ExchangeCompletionListener; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import org.wildfly.event.logger.EventLogger; /** * An HTTP handler that writes exchange attributes to an event logger. * * @author <a href="mailto:[email protected]">James R. Perkins</a> */ class EventLoggerHttpHandler implements HttpHandler { private final HttpHandler next; private final ExchangeCompletionListener exchangeCompletionListener = new AccessLogCompletionListener(); private final Predicate predicate; private final Collection<AccessLogAttribute> attributes; private final EventLogger eventLogger; /** * Creates a new instance of the HTTP handler. * * @param next the next handler in the chain to invoke to invoke after this handler executes * @param predicate the predicate used to determine if this handler should execute * @param attributes the attributes which should be logged * @param eventLogger the event logger */ EventLoggerHttpHandler(final HttpHandler next, final Predicate predicate, final Collection<AccessLogAttribute> attributes, final EventLogger eventLogger) { this.next = next; this.predicate = predicate; this.attributes = attributes; this.eventLogger = eventLogger; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { exchange.addExchangeCompleteListener(exchangeCompletionListener); next.handleRequest(exchange); } private class AccessLogCompletionListener implements ExchangeCompletionListener { @Override public void exchangeEvent(final HttpServerExchange exchange, final NextListener nextListener) { try { if (predicate == null || predicate.resolve(exchange)) { final Map<String, Object> data = new LinkedHashMap<>(); for (AccessLogAttribute attribute : attributes) { data.put(attribute.getKey(), attribute.resolveAttribute(exchange)); } eventLogger.log(data); } } finally { nextListener.proceed(); } } } }
3,081
37.049383
108
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/JSPConfig.java
/* * 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.ServletInfo; import org.apache.jasper.servlet.JspServlet; /** * @author Tomaz Cerar (c) 2013 Red Hat Inc. */ public class JSPConfig { private final ServletInfo servletInfo; public JSPConfig(final boolean developmentMode, final boolean disabled, final boolean keepGenerated, final boolean trimSpaces, final boolean tagPooling, final boolean mappedFile, final int checkInterval, int modificationTestInterval, final boolean recompileOnFail, boolean smap, boolean dumpSmap, boolean genStringAsCharArray, boolean errorOnUseBeanInvalidClassAttribute, String scratchDir, String sourceVm, String targetVm, String javaEncoding, boolean xPoweredBy, boolean displaySourceFragment, boolean optimizeScriptlets) { if (disabled) { servletInfo = null; } else { final io.undertow.servlet.api.ServletInfo jspServlet = new ServletInfo("jsp", JspServlet.class); jspServlet.setRequireWelcomeFileMapping(true); jspServlet.addInitParam("development", Boolean.toString(developmentMode)); jspServlet.addInitParam("keepgenerated", Boolean.toString(keepGenerated)); jspServlet.addInitParam("trimSpaces", Boolean.toString(trimSpaces)); jspServlet.addInitParam("enablePooling", Boolean.toString(tagPooling)); jspServlet.addInitParam("mappedfile", Boolean.toString(mappedFile)); jspServlet.addInitParam("checkInterval", Integer.toString(checkInterval)); jspServlet.addInitParam("modificationTestInterval", Integer.toString(modificationTestInterval)); jspServlet.addInitParam("recompileOnFail", Boolean.toString(recompileOnFail)); jspServlet.addInitParam("suppressSmap", Boolean.toString(!smap)); jspServlet.addInitParam("dumpSmap", Boolean.toString(dumpSmap)); jspServlet.addInitParam("genStringAsCharArray", Boolean.toString(genStringAsCharArray)); jspServlet.addInitParam("errorOnUseBeanInvalidClassAttribute", Boolean.toString(errorOnUseBeanInvalidClassAttribute)); jspServlet.addInitParam("optimizeScriptlets", Boolean.toString(optimizeScriptlets)); if (scratchDir != null) { jspServlet.addInitParam("scratchdir", scratchDir); } // jasper will find the right defaults. jspServlet.addInitParam("compilerSourceVM", sourceVm); jspServlet.addInitParam("compilerTargetVM", targetVm); jspServlet.addInitParam("javaEncoding", javaEncoding); jspServlet.addInitParam("xpoweredBy", Boolean.toString(xPoweredBy)); jspServlet.addInitParam("displaySourceFragment", Boolean.toString(displaySourceFragment)); this.servletInfo = jspServlet; } } public ServletInfo createJSPServletInfo() { if(servletInfo == null) { return null; } return servletInfo.clone(); } }
4,167
49.216867
130
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/WebServerService.java
/* * 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.HashMap; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import org.jboss.as.network.SocketBinding; import org.jboss.as.web.host.CommonWebServer; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class WebServerService implements CommonWebServer, Service<WebServerService> { private final Consumer<WebServerService> serviceConsumer; private final Supplier<Server> server; WebServerService(final Consumer<WebServerService> serviceConsumer, final Supplier<Server> server) { this.serviceConsumer = serviceConsumer; this.server = server; } //todo we need to handle cases when deployments reference listeners/server/host directly @Override public int getPort(final String protocol, final boolean secure) { Map<String, UndertowListener> listeners = getListenerMap(); UndertowListener listener = null; for (Map.Entry<String, UndertowListener> entry : listeners.entrySet()) { if (protocol.toLowerCase().contains(entry.getKey())) { listener = entry.getValue(); } } if (listener != null && listener.getProtocol() == HttpListenerService.PROTOCOL && secure) { if (listeners.containsKey(HttpsListenerService.PROTOCOL)) { listener = listeners.get(HttpsListenerService.PROTOCOL); } else { UndertowLogger.ROOT_LOGGER.secureListenerNotAvailableForPort(protocol); } } if (listener != null) { SocketBinding binding = listener.getSocketBinding(); return binding.getAbsolutePort(); } throw UndertowLogger.ROOT_LOGGER.noPortListeningForProtocol(protocol); } private Map<String, UndertowListener> getListenerMap() { HashMap<String, UndertowListener> listeners = new HashMap<>(); for (UndertowListener listener : server.get().getListeners()) { listeners.put(listener.getProtocol(), listener); } return listeners; } @Override public void start(final StartContext context) { serviceConsumer.accept(this); } @Override public void stop(final StopContext context) { serviceConsumer.accept(null); } @Override public WebServerService getValue() { return this; } }
3,675
36.510204
103
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowSubsystemSchema.java
/* * JBoss, Home of Professional Open Source. * Copyright 2022, 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.PersistentResourceXMLDescription; import org.jboss.as.controller.PersistentSubsystemSchema; import org.jboss.as.controller.SubsystemSchema; import org.jboss.as.controller.xml.VersionedNamespace; import org.jboss.staxmapper.IntVersion; /** * Enumerates the supported Undertow subsystem schemas. * @author Paul Ferraro */ public enum UndertowSubsystemSchema implements PersistentSubsystemSchema<UndertowSubsystemSchema> { /* Unsupported, for documentation purposes only VERSION_1_0(1, 0), // WildFly 8.0 VERSION_1_1(1, 1), // WildFly 8.1 VERSION_1_2(1, 2), // WildFly 8.2 VERSION_2_0(2), // WildFly 9 VERSION_3_0(3, 0), // WildFly 10.0 */ VERSION_3_1(3, 1), // WildFly 10.1 VERSION_4_0(4), // WildFly 11 VERSION_5_0(5), // WildFly 12 VERSION_6_0(6), // WildFly 13 VERSION_7_0(7), // WildFly 14 VERSION_8_0(8), // WildFly 15-16 VERSION_9_0(9), // WildFly 17 VERSION_10_0(10), // WildFly 18-19 VERSION_11_0(11), // WildFly 20-22 N.B. There were no parser changes between 10.0 and 11.0 !! VERSION_12_0(12), // WildFly 23-26.1, EAP 7.4 VERSION_13_0(13), // WildFly 27 N.B. There were no schema changes between 12.0 and 13.0! VERSION_14_0(14), // WildFly 28-present ; static final UndertowSubsystemSchema CURRENT = VERSION_14_0; private final VersionedNamespace<IntVersion, UndertowSubsystemSchema> namespace; UndertowSubsystemSchema(int major) { this(new IntVersion(major)); } UndertowSubsystemSchema(int major, int minor) { this(new IntVersion(major, minor)); } UndertowSubsystemSchema(IntVersion version) { this.namespace = SubsystemSchema.createLegacySubsystemURN(UndertowExtension.SUBSYSTEM_NAME, version); } @Override public VersionedNamespace<IntVersion, UndertowSubsystemSchema> getNamespace() { return this.namespace; } @Override public PersistentResourceXMLDescription getXMLDescription() { return UndertowPersistentResourceXMLDescriptionFactory.INSTANCE.apply(this); } }
3,203
38.073171
109
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/AbstractPersistentSessionManager.java
/* * 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.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; import java.util.function.Consumer; import java.util.function.Supplier; /** * Persistent session manager * * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public abstract class AbstractPersistentSessionManager implements SessionPersistenceManager, Service<SessionPersistenceManager> { public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("undertow", "persistent-session-manager"); private final Consumer<SessionPersistenceManager> serviceConsumer; private final Supplier<ModuleLoader> moduleLoader; private MarshallerFactory factory; private MarshallingConfiguration configuration; AbstractPersistentSessionManager(final Consumer<SessionPersistenceManager> serviceConsumer, final Supplier<ModuleLoader> moduleLoader) { this.serviceConsumer = serviceConsumer; this.moduleLoader = moduleLoader; } @Override public void persistSessions(String deploymentName, Map<String, PersistentSession> sessionData) { try { final Marshaller marshaller = createMarshaller(); try { final Map<String, SessionEntry> serializedData = new HashMap<String, SessionEntry>(); for (Map.Entry<String, PersistentSession> sessionEntry : sessionData.entrySet()) { Map<String, byte[]> data = new HashMap<String, byte[]>(); for (Map.Entry<String, Object> 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<String, SessionEntry> serializedData) throws IOException; protected abstract Map<String, SessionEntry> loadSerializedSessions(final String deploymentName) throws IOException; @Override public Map<String, PersistentSession> loadSessionAttributes(String deploymentName, final ClassLoader classLoader) { try { Unmarshaller unmarshaller = createUnmarshaller(); try { long time = System.currentTimeMillis(); Map<String, SessionEntry> data = loadSerializedSessions(deploymentName); if (data != null) { Map<String, PersistentSession> ret = new HashMap<String, PersistentSession>(); for (Map.Entry<String, SessionEntry> sessionEntry : data.entrySet()) { if (sessionEntry.getValue().expiry.getTime() > time) { Map<String, Object> session = new HashMap<String, Object>(); for (Map.Entry<String, byte[]> 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 void start(final StartContext startContext) throws StartException { final RiverMarshallerFactory factory = new RiverMarshallerFactory(); final MarshallingConfiguration configuration = new MarshallingConfiguration(); configuration.setClassResolver(ModularClassResolver.getInstance(moduleLoader.get())); this.configuration = configuration; this.factory = factory; this.serviceConsumer.accept(this); } @Override public void stop(final StopContext stopContext) { this.serviceConsumer.accept(null); } @Override public SessionPersistenceManager getValue() { return this; } protected static final class SessionEntry implements Serializable { private final Date expiry; private final Map<String, byte[]> data; private SessionEntry(Date expiry, Map<String, byte[]> data) { this.expiry = expiry; this.data = data; } public Date getExpiry() { return expiry; } public Map<String, byte[]> getData() { return data; } } }
8,081
41.989362
169
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/WebHostService.java
/* * 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.Map; import java.util.function.Consumer; import java.util.function.Supplier; import jakarta.servlet.Servlet; import io.undertow.server.HttpHandler; import io.undertow.server.handlers.resource.PathResourceManager; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.DeploymentManager; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.util.ImmediateInstanceFactory; import org.jboss.as.web.host.ServletBuilder; import org.jboss.as.web.host.WebDeploymentBuilder; import org.jboss.as.web.host.WebDeploymentController; import org.jboss.as.web.host.WebHost; import org.jboss.msc.service.Service; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StopContext; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.requestcontroller.RequestController; import org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler; /** * Implementation of WebHost from common web, service starts with few more dependencies than default Host * * @author Tomaz Cerar (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class WebHostService implements Service<WebHost>, WebHost { private final Consumer<WebHost> webHostConsumer; private final Supplier<Server> server; private final Supplier<Host> host; private final Supplier<RequestController> requestController; private volatile ControlPoint controlPoint; WebHostService(final Consumer<WebHost> webHostConsumer, final Supplier<Server> server, final Supplier<Host> host, final Supplier<RequestController> requestController) { this.webHostConsumer = webHostConsumer; this.server = server; this.host = host; this.requestController = requestController; } @Override public WebDeploymentController addWebDeployment(final WebDeploymentBuilder webDeploymentBuilder) { DeploymentInfo d = new DeploymentInfo(); d.setDeploymentName(webDeploymentBuilder.getContextRoot()); d.setContextPath(webDeploymentBuilder.getContextRoot()); d.setClassLoader(webDeploymentBuilder.getClassLoader()); d.setResourceManager(new PathResourceManager(webDeploymentBuilder.getDocumentRoot().toPath().toAbsolutePath(), 1024L * 1024L)); d.setIgnoreFlush(false); for (ServletBuilder servlet : webDeploymentBuilder.getServlets()) { ServletInfo s; if (servlet.getServlet() == null) { s = new ServletInfo(servlet.getServletName(), (Class<? extends Servlet>) servlet.getServletClass()); } else { s = new ServletInfo(servlet.getServletName(), (Class<? extends Servlet>) servlet.getServletClass(), new ImmediateInstanceFactory<>(servlet.getServlet())); } if (servlet.isForceInit()) { s.setLoadOnStartup(1); } s.addMappings(servlet.getUrlMappings()); for (Map.Entry<String, String> param : servlet.getInitParams().entrySet()) { s.addInitParam(param.getKey(), param.getValue()); } d.addServlet(s); } if (controlPoint != null) { d.addOuterHandlerChainWrapper(GlobalRequestControllerHandler.wrapper(controlPoint, webDeploymentBuilder.getAllowRequestPredicates())); } return new WebDeploymentControllerImpl(d); } private class WebDeploymentControllerImpl implements WebDeploymentController { private final DeploymentInfo deploymentInfo; private volatile DeploymentManager manager; private WebDeploymentControllerImpl(final DeploymentInfo deploymentInfo) { this.deploymentInfo = deploymentInfo; } @Override public void create() throws Exception { ServletContainer container = server.get().getServletContainer().getServletContainer(); manager = container.addDeployment(deploymentInfo); manager.deploy(); } @Override public void start() throws Exception { HttpHandler handler = manager.start(); host.get().registerDeployment(manager.getDeployment(), handler); } @Override public void stop() throws Exception { host.get().unregisterDeployment(manager.getDeployment()); manager.stop(); } @Override public void destroy() throws Exception { manager.undeploy(); ServletContainer container = server.get().getServletContainer().getServletContainer(); container.removeDeployment(deploymentInfo); } } @Override public void start(final StartContext context) { RequestController rq = requestController != null ? requestController.get() : null; if (rq != null) { controlPoint = rq.getControlPoint("", "org.wildfly.undertow.webhost." + server.get().getName() + "." + host.get().getName()); } webHostConsumer.accept(this); } @Override public void stop(final StopContext context) { webHostConsumer.accept(null); if (controlPoint != null) { requestController.get().removeControlPoint(controlPoint); } } @Override public WebHost getValue() throws IllegalStateException, IllegalArgumentException { return this; } }
6,558
40.512658
170
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/DeploymentWebSocketDefinition.java
/* * 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 { 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(); DeploymentWebSocketDefinition() { super(PathElement.pathElement("websocket"), UndertowExtension.getResolver("deployment.websocket")); } @Override public void registerAttributes(ManagementResourceRegistration registration) { registration.registerReadOnlyAttribute(PATH, null); registration.registerReadOnlyAttribute(ENDPOINT_CLASS, null); } }
2,215
41.615385
168
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/Namespace.java
/* * 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 <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. */ enum Namespace { // must be first UNKNOWN(null), UNDERTOW_1_0("urn:jboss:domain:undertow:1.0"), UNDERTOW_1_1("urn:jboss:domain:undertow:1.1"), UNDERTOW_1_2("urn:jboss:domain:undertow:1.2"), UNDERTOW_2_0("urn:jboss:domain:undertow:2.0"), UNDERTOW_3_0("urn:jboss:domain:undertow:3.0"), UNDERTOW_3_1("urn:jboss:domain:undertow:3.1"), UNDERTOW_4_0("urn:jboss:domain:undertow:4.0"), UNDERTOW_5_0("urn:jboss:domain:undertow:5.0"), UNDERTOW_6_0("urn:jboss:domain:undertow:6.0"), UNDERTOW_7_0("urn:jboss:domain:undertow:7.0"), UNDERTOW_8_0("urn:jboss:domain:undertow:8.0"), UNDERTOW_9_0("urn:jboss:domain:undertow:9.0"), UNDERTOW_10_0("urn:jboss:domain:undertow:10.0"), UNDERTOW_11_0("urn:jboss:domain:undertow:11.0"), UNDERTOW_12_0("urn:jboss:domain:undertow:12.0"), UNDERTOW_13_0("urn:jboss:domain:undertow:13.0"), ; /** * The current namespace version. */ public static final Namespace CURRENT = UNDERTOW_13_0; private final String name; Namespace(final String name) { this.name = name; } /** * Get the URI of this namespace. * * @return the URI */ public String getUriString() { return name; } }
2,414
33.014085
88
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/SingleSignOnSessionFactoryServiceNameProvider.java
/* * 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.msc.service.ServiceName; import org.wildfly.clustering.service.ServiceNameProvider; /** * @author Paul Ferraro */ public class SingleSignOnSessionFactoryServiceNameProvider implements ServiceNameProvider { private final ServiceName name; public SingleSignOnSessionFactoryServiceNameProvider(String securityDomainName) { this.name = ApplicationSecurityDomainDefinition.APPLICATION_SECURITY_DOMAIN_RUNTIME_CAPABILITY.fromBaseCapability(securityDomainName).getCapabilityServiceName().append("sso", "factory"); } @Override public ServiceName getServiceName() { return this.name; } }
1,707
37.818182
194
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/RemoteHttpInvokerService.java
/* * 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.CookieImpl; import io.undertow.server.session.SecureRandomSessionIdGenerator; 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 io.undertow.server.handlers.PathHandler; /** * Service that exposes the Wildfly * * @author Stuart Douglas */ public class RemoteHttpInvokerService implements Service<PathHandler> { private static final String AFFINITY_PATH = "/common/v1/affinity"; private final PathHandler pathHandler = new PathHandler(); @Override public void start(StartContext context) throws StartException { pathHandler.clearPaths(); SecureRandomSessionIdGenerator generator = new SecureRandomSessionIdGenerator(); pathHandler.addPrefixPath(AFFINITY_PATH, exchange -> { String resolved = exchange.getResolvedPath(); int index = resolved.lastIndexOf(AFFINITY_PATH); if(index > 0) { resolved = resolved.substring(0, index); } exchange.getResponseCookies().put("JSESSIONID", new CookieImpl("JSESSIONID", generator.createSessionId()).setPath(resolved)); }); } @Override public void stop(StopContext context) { pathHandler.clearPaths(); } @Override public PathHandler getValue() throws IllegalStateException, IllegalArgumentException { return pathHandler; } }
2,561
36.130435
137
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowListener.java
/* * 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.network.SocketBinding; /** * Represents the externally accessible interface provided by Undertow's listeners * * @author Stuart Douglas */ public interface UndertowListener { /** * Returns the listeners socket binding. * * @return The listeners socket binding */ SocketBinding getSocketBinding(); /** * Returns true if the listener is secure. In general this will be true for HTTPS listeners, however other listener * types may have been explicitly marked as secure. * * @return <code>true</code> if the listener is considered security */ boolean isSecure(); /** * Returns the transport protocol. This will generally either be http, https or ajp. * * @return The transport protocol */ String getProtocol(); /** * Returns the listener name * * @return The listener name */ String getName(); /** * Returns the server this listener is registered with. * * @return the server this listener is registered with */ Server getServer(); /** * Returns true if the listener has shut down. * * @return <code>true</code> if the listener has been shutdown */ boolean isShutdown(); }
2,338
29.376623
119
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ApplicationSecurityDomainSingleSignOnDefinition.java
/* * 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.EnumSet; 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.ReloadRequiredResourceRegistrar; 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.as.controller.security.CredentialReferenceWriteAttributeHandler; 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<Void> definition; Capability(String name) { this.definition = RuntimeCapability.Builder.of(name, true).setDynamicNameMapper(UnaryCapabilityNameResolver.PARENT).build(); } @Override public RuntimeCapability<Void> 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<SimpleAttributeDefinitionBuilder> 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(EnumSet.complementOf(EnumSet.of(Attribute.CREDENTIAL))) .addAttribute(Attribute.CREDENTIAL, new CredentialReferenceWriteAttributeHandler(Attribute.CREDENTIAL.getDefinition())) .addAttributes(SingleSignOnDefinition.Attribute.class) .addCapabilities(Capability.class) ; new ReloadRequiredResourceRegistrar(descriptor).register(registration); } }
5,229
52.917526
333
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HostRemove.java
/* * 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 <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. */ class HostRemove extends AbstractRemoveStepHandler { @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { if (context.isResourceServiceRestartAllowed()) { 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); } else { context.reloadRequired(); } } protected void recoverServices(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { if (context.isResourceServiceRestartAllowed()) { HostAdd.INSTANCE.performRuntime(context, operation, model); } else { context.revertReloadRequired(); } } }
3,217
47.029851
132
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ExchangeAttributeDefinitions.java
/* * Copyright 2019 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.extension.undertow; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.VALUE; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.concurrent.TimeUnit; import java.util.function.Function; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import io.undertow.attribute.AuthenticationTypeExchangeAttribute; import io.undertow.attribute.BytesSentAttribute; import io.undertow.attribute.DateTimeAttribute; import io.undertow.attribute.ExchangeAttribute; import io.undertow.attribute.HostAndPortAttribute; import io.undertow.attribute.LocalIPAttribute; import io.undertow.attribute.LocalPortAttribute; import io.undertow.attribute.LocalServerNameAttribute; import io.undertow.attribute.PathParameterAttribute; import io.undertow.attribute.PredicateContextAttribute; import io.undertow.attribute.QueryParameterAttribute; import io.undertow.attribute.QueryStringAttribute; import io.undertow.attribute.RelativePathAttribute; import io.undertow.attribute.RemoteHostAttribute; import io.undertow.attribute.RemoteIPAttribute; import io.undertow.attribute.RemoteObfuscatedIPAttribute; import io.undertow.attribute.RemoteUserAttribute; import io.undertow.attribute.RequestHeaderAttribute; import io.undertow.attribute.RequestLineAttribute; import io.undertow.attribute.RequestMethodAttribute; import io.undertow.attribute.RequestPathAttribute; import io.undertow.attribute.RequestProtocolAttribute; import io.undertow.attribute.RequestSchemeAttribute; import io.undertow.attribute.RequestURLAttribute; import io.undertow.attribute.ResolvedPathAttribute; import io.undertow.attribute.ResponseCodeAttribute; import io.undertow.attribute.ResponseHeaderAttribute; import io.undertow.attribute.ResponseReasonPhraseAttribute; import io.undertow.attribute.ResponseTimeAttribute; import io.undertow.attribute.SecureExchangeAttribute; import io.undertow.attribute.SslCipherAttribute; import io.undertow.attribute.SslClientCertAttribute; import io.undertow.attribute.SslSessionIdAttribute; import io.undertow.attribute.StoredResponse; import io.undertow.attribute.ThreadNameAttribute; import io.undertow.attribute.TransportProtocolAttribute; import io.undertow.util.HttpString; import org.jboss.as.controller.AbstractAttributeDefinitionBuilder; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.AttributeMarshaller; import org.jboss.as.controller.AttributeParser; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.ObjectTypeAttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.SimpleAttributeDefinition; import org.jboss.as.controller.SimpleAttributeDefinitionBuilder; import org.jboss.as.controller.StringListAttributeDefinition; import org.jboss.as.controller.operations.validation.EnumValidator; import org.jboss.as.controller.operations.validation.ModelTypeValidator; import org.jboss.as.controller.parsing.ParseUtils; import org.jboss.dmr.ModelNode; import org.jboss.dmr.ModelType; import org.jboss.staxmapper.XMLExtendedStreamReader; import org.wildfly.common.function.ExceptionBiFunction; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @SuppressWarnings({"Convert2Lambda", "Anonymous2MethodRef"}) class ExchangeAttributeDefinitions { private static final String KEY_NAME = "key"; private static final SimpleAttributeDefinitionBuilder KEY_BUILDER = SimpleAttributeDefinitionBuilder.create(KEY_NAME, ModelType.STRING, true); private static final Map<AttributeDefinition, ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>> ATTRIBUTE_RESOLVERS = new HashMap<>(); private static final SimpleAttributeDefinitionBuilder KEY_PREFIX_BUILDER = SimpleAttributeDefinitionBuilder.create("key-prefix", ModelType.STRING, true); private static final StringListAttributeDefinition NAMES = StringListAttributeDefinition.Builder.of("names") .setAllowExpression(true) .setAttributeMarshaller(new AttributeMarshaller.AttributeElementMarshaller() { @Override public void marshallAsElement(final AttributeDefinition attribute, final ModelNode resourceModel, final boolean marshallDefault, final XMLStreamWriter writer) throws XMLStreamException { assert attribute instanceof StringListAttributeDefinition; try { final List<String> list = ((StringListAttributeDefinition) attribute).unwrap(ExpressionResolver.SIMPLE, resourceModel); if (list.isEmpty()) { return; } if (resourceModel.hasDefined(attribute.getName())) { for (ModelNode value : resourceModel.get(attribute.getName()).asList()) { writer.writeStartElement(attribute.getXmlName()); writer.writeAttribute(VALUE, value.asString()); writer.writeEndElement(); } } } catch (OperationFailedException e) { throw new XMLStreamException(e); } } }) .setAttributeParser(new AttributeParser() { @Override public boolean isParseAsElement() { return true; } @Override public void parseElement(final AttributeDefinition attribute, final XMLExtendedStreamReader reader, final ModelNode operation) throws XMLStreamException { ParseUtils.requireSingleAttribute(reader, VALUE); final String value = reader.getAttributeValue(0); operation.get(attribute.getName()).add(value); ParseUtils.requireNoContent(reader); } }) .setRequired(true) .setXmlName("name") .build(); private static final SimpleAttributeDefinition AUTHENTICATION_TYPE_KEY = createKey("authenticationType"); private static final ObjectTypeAttributeDefinition AUTHENTICATION_TYPE = create( ObjectTypeAttributeDefinition.create("authentication-type", AUTHENTICATION_TYPE_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(AUTHENTICATION_TYPE_KEY, context, model, AuthenticationTypeExchangeAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition BYTES_SENT_KEY = createKey("bytesSent"); private static final ObjectTypeAttributeDefinition BYTES_SENT = create( ObjectTypeAttributeDefinition.create("bytes-sent", BYTES_SENT_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(BYTES_SENT_KEY, context, model, new BytesSentAttribute(false), new Function<String, Object>() { @Override public Object apply(final String s) { return Long.valueOf(s); } }); } }); private static final SimpleAttributeDefinition DATE_TIME_KEY = createKey("dateTime"); private static final SimpleAttributeDefinition DATE_FORMAT = SimpleAttributeDefinitionBuilder.create("date-format", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new ModelTypeValidator(ModelType.STRING, true, true) { @Override public void validateParameter(final String parameterName, final ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); try { new SimpleDateFormat(value.asString()); } catch (IllegalArgumentException ignore) { throw UndertowLogger.ROOT_LOGGER.invalidDateTimeFormatterPattern(value.asString()); } } }) .build(); private static final SimpleAttributeDefinition TIME_ZONE = SimpleAttributeDefinitionBuilder.create("time-zone", ModelType.STRING, true) .setAllowExpression(true) .setValidator(new ModelTypeValidator(ModelType.STRING, true, true) { private final List<String> zoneIds = Arrays.asList(TimeZone.getAvailableIDs()); @Override public void validateParameter(final String parameterName, final ModelNode value) throws OperationFailedException { super.validateParameter(parameterName, value); if (!zoneIds.contains(value.asString())) { throw UndertowLogger.ROOT_LOGGER.invalidTimeZoneId(value.asString()); } } }) .build(); private static final ObjectTypeAttributeDefinition DATE_TIME = create( ObjectTypeAttributeDefinition.create("date-time", DATE_TIME_KEY, DATE_FORMAT, TIME_ZONE), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { final ExchangeAttribute exchangeAttribute; if (model.hasDefined(DATE_FORMAT.getName())) { String timeZone = null; if (model.hasDefined(TIME_ZONE.getName())) { timeZone = TIME_ZONE.resolveModelAttribute(context, model).asString(); } exchangeAttribute = new DateTimeAttribute(DATE_FORMAT.resolveModelAttribute(context, model).asString(), timeZone); } else { exchangeAttribute = DateTimeAttribute.INSTANCE; } return createSingleton(DATE_TIME_KEY, context, model, exchangeAttribute); } }); private static final SimpleAttributeDefinition HOST_AND_PORT_KEY = createKey("hostAndPort"); private static final ObjectTypeAttributeDefinition HOST_AND_PORT = create( ObjectTypeAttributeDefinition.create("host-and-port", HOST_AND_PORT_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(HOST_AND_PORT_KEY, context, model, HostAndPortAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition LOCAL_IP_KEY = createKey("localIp"); private static final ObjectTypeAttributeDefinition LOCAL_IP = create( ObjectTypeAttributeDefinition.create("local-ip", LOCAL_IP_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(LOCAL_IP_KEY, context, model, LocalIPAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition LOCAL_PORT_KEY = createKey("localPort"); private static final ObjectTypeAttributeDefinition LOCAL_PORT = create( ObjectTypeAttributeDefinition.create("local-port", LOCAL_PORT_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(LOCAL_PORT_KEY, context, model, LocalPortAttribute.INSTANCE, new Function<String, Object>() { @Override public Object apply(final String s) { return Integer.valueOf(s); } }); } }); private static final SimpleAttributeDefinition LOCAL_SERVER_NAME_KEY = createKey("localServerName"); private static final ObjectTypeAttributeDefinition LOCAL_SERVER_NAME = create( ObjectTypeAttributeDefinition.create("local-server-name", LOCAL_SERVER_NAME_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(LOCAL_SERVER_NAME_KEY, context, model, LocalServerNameAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition PATH_PARAMETER_KEY_PREFIX = KEY_PREFIX_BUILDER.build(); private static final ObjectTypeAttributeDefinition PATH_PARAMETER = create(ObjectTypeAttributeDefinition.Builder.of("path-parameter", PATH_PARAMETER_KEY_PREFIX, NAMES), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { final Collection<AccessLogAttribute> result = new ArrayList<>(5); for (ModelNode m : NAMES.resolveModelAttribute(context, model).asList()) { final String name = m.asString(); final String keyName = resolveKeyName(PATH_PARAMETER_KEY_PREFIX.resolveModelAttribute(context, model), name); result.add(AccessLogAttribute.of(keyName, new PathParameterAttribute(name))); } return result; } }); private static final SimpleAttributeDefinition PREDICATE_KEY_PREFIX = KEY_PREFIX_BUILDER.build(); private static final ObjectTypeAttributeDefinition PREDICATE = create(ObjectTypeAttributeDefinition.Builder.of("predicate", PREDICATE_KEY_PREFIX, NAMES), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { final Collection<AccessLogAttribute> result = new ArrayList<>(5); for (ModelNode m : NAMES.resolveModelAttribute(context, model).asList()) { final String predicateName = m.asString(); final String keyName = resolveKeyName(PREDICATE_KEY_PREFIX.resolveModelAttribute(context, model), predicateName); result.add(AccessLogAttribute.of(keyName, new PredicateContextAttribute(predicateName))); } return result; } }); private static final SimpleAttributeDefinition QUERY_PARAMETER_KEY_PREFIX = KEY_PREFIX_BUILDER.build(); private static final ObjectTypeAttributeDefinition QUERY_PARAMETER = create(ObjectTypeAttributeDefinition.Builder.of("query-parameter", QUERY_PARAMETER_KEY_PREFIX, NAMES), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { final Collection<AccessLogAttribute> result = new ArrayList<>(5); for (ModelNode m : NAMES.resolveModelAttribute(context, model).asList()) { final String paramName = m.asString(); final String keyName = resolveKeyName(QUERY_PARAMETER_KEY_PREFIX.resolveModelAttribute(context, model), paramName); result.add(AccessLogAttribute.of(keyName, new QueryParameterAttribute(paramName))); } return result; } }); private static final SimpleAttributeDefinition QUERY_STRING_KEY = createKey("queryString"); private static final SimpleAttributeDefinition INCLUDE_QUESTION_MARK = SimpleAttributeDefinitionBuilder .create("include-question-mark", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); private static final ObjectTypeAttributeDefinition QUERY_STRING = create( ObjectTypeAttributeDefinition.create("query-string", QUERY_STRING_KEY, INCLUDE_QUESTION_MARK), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { if (INCLUDE_QUESTION_MARK.resolveModelAttribute(context, model).asBoolean()) { return createSingleton(QUERY_STRING_KEY, context, model, QueryStringAttribute.INSTANCE); } return createSingleton(QUERY_STRING_KEY, context, model, QueryStringAttribute.BARE_INSTANCE); } }); private static final SimpleAttributeDefinition RELATIVE_PATH_KEY = createKey("relativePath"); private static final ObjectTypeAttributeDefinition RELATIVE_PATH = create( ObjectTypeAttributeDefinition.create("relative-path", RELATIVE_PATH_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(RELATIVE_PATH_KEY, context, model, RelativePathAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REMOTE_HOST_KEY = createKey("remoteHost"); private static final ObjectTypeAttributeDefinition REMOTE_HOST = create( ObjectTypeAttributeDefinition.create("remote-host", REMOTE_HOST_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(REMOTE_HOST_KEY, context, model, RemoteHostAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REMOTE_IP_KEY = createKey("remoteIp"); private static final SimpleAttributeDefinition OBFUSCATED = SimpleAttributeDefinitionBuilder.create("obfuscated", ModelType.BOOLEAN, true) .setAllowExpression(true) .setDefaultValue(ModelNode.FALSE) .build(); private static final ObjectTypeAttributeDefinition REMOTE_IP = create( ObjectTypeAttributeDefinition.create("remote-ip", REMOTE_IP_KEY, OBFUSCATED), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { if (OBFUSCATED.resolveModelAttribute(context, model).asBoolean()) { return createSingleton(REMOTE_IP_KEY, context, model, RemoteObfuscatedIPAttribute.INSTANCE); } return createSingleton(REMOTE_IP_KEY, context, model, RemoteIPAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REMOTE_USER_KEY = createKey("remoteUser"); private static final ObjectTypeAttributeDefinition REMOTE_USER = create( ObjectTypeAttributeDefinition.create("remote-user", REMOTE_USER_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(REMOTE_USER_KEY, context, model, RemoteUserAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REQUEST_HEADER_KEY_PREFIX = KEY_PREFIX_BUILDER.build(); private static final ObjectTypeAttributeDefinition REQUEST_HEADER = create(ObjectTypeAttributeDefinition.Builder.of("request-header", REQUEST_HEADER_KEY_PREFIX, NAMES), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { final Collection<AccessLogAttribute> result = new ArrayList<>(5); for (ModelNode m : NAMES.resolveModelAttribute(context, model).asList()) { final String name = m.asString(); final String keyName = resolveKeyName(REQUEST_HEADER_KEY_PREFIX.resolveModelAttribute(context, model), name); result.add(AccessLogAttribute.of(keyName, new RequestHeaderAttribute(HttpString.tryFromString(name)))); } return result; } }); private static final SimpleAttributeDefinition REQUEST_LINE_KEY = createKey("requestLine"); private static final ObjectTypeAttributeDefinition REQUEST_LINE = create( ObjectTypeAttributeDefinition.create("request-line", REQUEST_LINE_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(REQUEST_LINE_KEY, context, model, RequestLineAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REQUEST_METHOD_KEY = createKey("requestMethod"); private static final ObjectTypeAttributeDefinition REQUEST_METHOD = create( ObjectTypeAttributeDefinition.create("request-method", REQUEST_METHOD_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(REQUEST_METHOD_KEY, context, model, RequestMethodAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REQUEST_PATH_KEY = createKey("requestPath"); private static final ObjectTypeAttributeDefinition REQUEST_PATH = create( ObjectTypeAttributeDefinition.create("request-path", REQUEST_PATH_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(REQUEST_PATH_KEY, context, model, RequestPathAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REQUEST_PROTOCOL_KEY = createKey("requestProtocol"); private static final ObjectTypeAttributeDefinition REQUEST_PROTOCOL = create( ObjectTypeAttributeDefinition.create("request-protocol", REQUEST_PROTOCOL_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(REQUEST_PROTOCOL_KEY, context, model, RequestProtocolAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REQUEST_SCHEME_KEY = createKey("requestScheme"); private static final ObjectTypeAttributeDefinition REQUEST_SCHEME = create( ObjectTypeAttributeDefinition.create("request-scheme", REQUEST_SCHEME_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(REQUEST_SCHEME_KEY, context, model, RequestSchemeAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition REQUEST_URL_KEY = createKey("requestUrl"); private static final ObjectTypeAttributeDefinition REQUEST_URL = create( ObjectTypeAttributeDefinition.create("request-url", REQUEST_URL_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(REQUEST_URL_KEY, context, model, RequestURLAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition RESOLVED_PATH_KEY = createKey("resolvedPath"); private static final ObjectTypeAttributeDefinition RESOLVED_PATH = create( ObjectTypeAttributeDefinition.create("resolved-path", RESOLVED_PATH_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(RESOLVED_PATH_KEY, context, model, ResolvedPathAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition RESPONSE_CODE_KEY = createKey("responseCode"); private static final ObjectTypeAttributeDefinition RESPONSE_CODE = create( ObjectTypeAttributeDefinition.create("response-code", RESPONSE_CODE_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(RESPONSE_CODE_KEY, context, model, ResponseCodeAttribute.INSTANCE, new Function<String, Object>() { @Override public Object apply(final String s) { return Integer.valueOf(s); } }); } }); private static final SimpleAttributeDefinition RESPONSE_HEADER_KEY_PREFIX = KEY_PREFIX_BUILDER.build(); private static final ObjectTypeAttributeDefinition RESPONSE_HEADER = create(ObjectTypeAttributeDefinition.Builder.of("response-header", RESPONSE_HEADER_KEY_PREFIX, NAMES), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { final Collection<AccessLogAttribute> result = new ArrayList<>(5); for (ModelNode m : NAMES.resolveModelAttribute(context, model).asList()) { final String name = m.asString(); final String keyName = resolveKeyName(RESPONSE_HEADER_KEY_PREFIX.resolveModelAttribute(context, model), name); result.add(AccessLogAttribute.of(keyName, new ResponseHeaderAttribute(HttpString.tryFromString(name)))); } return result; } }); private static final SimpleAttributeDefinition RESPONSE_REASON_PHRASE_KEY = createKey("responseReasonPhrase"); private static final ObjectTypeAttributeDefinition RESPONSE_REASON_PHRASE = create( ObjectTypeAttributeDefinition.create("response-reason-phrase", RESPONSE_REASON_PHRASE_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(RESPONSE_REASON_PHRASE_KEY, context, model, ResponseReasonPhraseAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition RESPONSE_TIME_KEY = createKey("responseTime"); private static final SimpleAttributeDefinition TIME_UNIT = new SimpleAttributeDefinitionBuilder("time-unit", ModelType.STRING, true) .setAllowExpression(true) .setDefaultValue(new ModelNode(TimeUnit.MILLISECONDS.name())) .setValidator(EnumValidator.create(TimeUnit.class, TimeUnit.SECONDS, TimeUnit.NANOSECONDS, TimeUnit.MILLISECONDS, TimeUnit.MICROSECONDS)) .build(); private static final ObjectTypeAttributeDefinition RESPONSE_TIME = create( ObjectTypeAttributeDefinition.create("response-time", RESPONSE_TIME_KEY, TIME_UNIT), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(RESPONSE_TIME_KEY, context, model, new ResponseTimeAttribute(TimeUnit.valueOf(TIME_UNIT.resolveModelAttribute(context, model).asString())), new Function<String, Object>() { @Override public Object apply(final String s) { if (s == null) { return null; } return Long.valueOf(s); } }); } }); private static final SimpleAttributeDefinition SECURE_EXCHANGE_KEY = createKey("secureExchange"); private static final ObjectTypeAttributeDefinition SECURE_EXCHANGE = create( ObjectTypeAttributeDefinition.create("secure-exchange", SECURE_EXCHANGE_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override @SuppressWarnings("Anonymous2MethodRef") public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(SECURE_EXCHANGE_KEY, context, model, SecureExchangeAttribute.INSTANCE, new Function<String, Object>() { @Override public Object apply(final String s) { return Boolean.valueOf(s); } }); } }); private static final SimpleAttributeDefinition SSL_CIPHER_KEY = createKey("sslCipher"); private static final ObjectTypeAttributeDefinition SSL_CIPHER = create( ObjectTypeAttributeDefinition.create("ssl-cipher", SSL_CIPHER_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(SSL_CIPHER_KEY, context, model, SslCipherAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition SSL_CLIENT_CERT_KEY = createKey("sslClientCert"); private static final ObjectTypeAttributeDefinition SSL_CLIENT_CERT = create( ObjectTypeAttributeDefinition.create("ssl-client-cert", SSL_CLIENT_CERT_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(SSL_CLIENT_CERT_KEY, context, model, SslClientCertAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition SSL_SESSION_ID_KEY = createKey("sslSessionId"); private static final ObjectTypeAttributeDefinition SSL_SESSION_ID = create( ObjectTypeAttributeDefinition.create("ssl-session-id", SSL_SESSION_ID_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(SSL_SESSION_ID_KEY, context, model, SslSessionIdAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition STORED_RESPONSE_KEY = createKey("storedResponse"); private static final ObjectTypeAttributeDefinition STORED_RESPONSE = create( ObjectTypeAttributeDefinition.create("stored-response", STORED_RESPONSE_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(STORED_RESPONSE_KEY, context, model, StoredResponse.INSTANCE); } }); private static final SimpleAttributeDefinition THREAD_NAME_KEY = createKey("threadName"); private static final ObjectTypeAttributeDefinition THREAD_NAME = create( ObjectTypeAttributeDefinition.create("thread-name", THREAD_NAME_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(THREAD_NAME_KEY, context, model, ThreadNameAttribute.INSTANCE); } }); private static final SimpleAttributeDefinition TRANSPORT_PROTOCOL_KEY = createKey("transportProtocol"); private static final ObjectTypeAttributeDefinition TRANSPORT_PROTOCOL = create( ObjectTypeAttributeDefinition.create("transport-protocol", TRANSPORT_PROTOCOL_KEY), new ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException>() { @Override public Collection<AccessLogAttribute> apply(final OperationContext context, final ModelNode model) throws OperationFailedException { return createSingleton(TRANSPORT_PROTOCOL_KEY, context, model, TransportProtocolAttribute.INSTANCE); } }); static final ObjectTypeAttributeDefinition ATTRIBUTES = ObjectTypeAttributeDefinition.create("attributes", AUTHENTICATION_TYPE, BYTES_SENT, DATE_TIME, HOST_AND_PORT, LOCAL_IP, LOCAL_PORT, LOCAL_SERVER_NAME, PATH_PARAMETER, PREDICATE, QUERY_PARAMETER, QUERY_STRING, RELATIVE_PATH, REMOTE_HOST, REMOTE_IP, REMOTE_USER, REQUEST_HEADER, REQUEST_LINE, REQUEST_METHOD, REQUEST_PATH, REQUEST_PROTOCOL, REQUEST_SCHEME, REQUEST_URL, RESOLVED_PATH, RESPONSE_CODE, RESPONSE_HEADER, RESPONSE_REASON_PHRASE, RESPONSE_TIME, SECURE_EXCHANGE, SSL_CIPHER, SSL_CLIENT_CERT, SSL_SESSION_ID, STORED_RESPONSE, THREAD_NAME, TRANSPORT_PROTOCOL ) .setDefaultValue(createDefaultAttribute()) .setRestartAllServices() .build(); static Collection<AccessLogAttribute> resolveAccessLogAttribute(final AttributeDefinition attribute, final OperationContext context, final ModelNode model) throws OperationFailedException { final ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException> attributeResolver = ATTRIBUTE_RESOLVERS.get(attribute); assert attributeResolver != null; if (model.hasDefined(attribute.getName())) { return attributeResolver.apply(context, model.get(attribute.getName())); } return Collections.emptyList(); } private static Collection<AccessLogAttribute> createSingleton(final AttributeDefinition keyAttribute, final OperationContext context, final ModelNode model, final ExchangeAttribute exchangeAttribute) throws OperationFailedException { return Collections.singletonList(AccessLogAttribute.of(keyAttribute.resolveModelAttribute(context, model).asString(), exchangeAttribute)); } @SuppressWarnings({"SameParameterValue"}) private static Collection<AccessLogAttribute> createSingleton(final AttributeDefinition keyAttribute, final OperationContext context, final ModelNode model, final ExchangeAttribute exchangeAttribute, final Function<String, Object> valueConverter) throws OperationFailedException { return Collections.singletonList(AccessLogAttribute.of(keyAttribute.resolveModelAttribute(context, model).asString(), exchangeAttribute, valueConverter)); } private static SimpleAttributeDefinition createKey(final String dftValue) { return KEY_BUILDER.setDefaultValue(new ModelNode(dftValue)).build(); } private static ModelNode createDefaultAttribute() { final ModelNode result = new ModelNode().setEmptyObject(); result.get(REMOTE_HOST.getName()).setEmptyObject(); result.get(REMOTE_USER.getName()).setEmptyObject(); result.get(DATE_TIME.getName()).setEmptyObject(); result.get(REQUEST_LINE.getName()).setEmptyObject(); result.get(RESPONSE_CODE.getName()).setEmptyObject(); result.get(BYTES_SENT.getName()).setEmptyObject(); return result; } private static <R extends AttributeDefinition, B extends AbstractAttributeDefinitionBuilder<B, R>> R create(final B builder, final ExceptionBiFunction<OperationContext, ModelNode, Collection<AccessLogAttribute>, OperationFailedException> attributeResolver) { final R result = builder.setRequired(false).build(); ATTRIBUTE_RESOLVERS.put(result, attributeResolver); return result; } private static String resolveKeyName(final ModelNode prefix, final String name) { final StringBuilder result = new StringBuilder(); if (prefix.isDefined()) { result.append(prefix.asString()); } result.append(name); return result.toString(); } }
43,677
60.605078
245
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ResetConnectorStatisticsHandler.java
/* * 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.ConnectorStatistics; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationDefinition; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.SimpleOperationDefinitionBuilder; import org.jboss.dmr.ModelNode; /** * Defines and handles resetting connector statistics * * @author Stuart Douglas */ public class ResetConnectorStatisticsHandler implements OperationStepHandler { public static final String OPERATION_NAME = "reset-statistics"; public static final OperationDefinition DEFINITION = new SimpleOperationDefinitionBuilder(OPERATION_NAME, UndertowExtension.getResolver("listener")) .setRuntimeOnly() .build(); public static final ResetConnectorStatisticsHandler INSTANCE = new ResetConnectorStatisticsHandler(); private ResetConnectorStatisticsHandler() { } public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ListenerService service = ListenerResourceDefinition.getListenerService(context); if (service != null) { ConnectorStatistics stats = service.getOpenListener().getConnectorStatistics(); if (stats != null) { stats.reset(); } } context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER); } }
2,531
38.5625
152
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/Server.java
/* * 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.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArraySet; import java.util.function.Consumer; import java.util.function.Supplier; import static java.nio.charset.StandardCharsets.UTF_8; import org.jboss.as.network.SocketBinding; 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 io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.CanonicalPathHandler; import io.undertow.server.handlers.NameVirtualHostHandler; import io.undertow.server.handlers.ResponseCodeHandler; import io.undertow.server.handlers.error.SimpleErrorPageHandler; import io.undertow.util.Headers; import org.wildfly.extension.undertow.logging.UndertowLogger; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class Server implements Service<Server> { private final Consumer<Server> serverConsumer; private final Supplier<ServletContainerService> servletContainer; private final Supplier<UndertowService> undertowService; private final String defaultHost; private final String name; private final NameVirtualHostHandler virtualHostHandler = new NameVirtualHostHandler(); private final List<ListenerService> listeners = new CopyOnWriteArrayList<>(); private final Set<Host> hosts = new CopyOnWriteArraySet<>(); private final HashMap<Integer,Integer> securePortMappings = new HashMap<>(); private volatile HttpHandler root; protected Server(final Consumer<Server> serverConsumer, final Supplier<ServletContainerService> servletContainer, final Supplier<UndertowService> undertowService, final String name, final String defaultHost) { this.serverConsumer = serverConsumer; this.servletContainer = servletContainer; this.undertowService = undertowService; this.name = name; this.defaultHost = defaultHost; } @Override public void start(StartContext startContext) throws StartException { root = virtualHostHandler; root = new SimpleErrorPageHandler(root); root = new CanonicalPathHandler(root); root = new DefaultHostHandler(root); UndertowLogger.ROOT_LOGGER.startedServer(name); undertowService.get().registerServer(this); serverConsumer.accept(this); } @Override public void stop(final StopContext stopContext) { serverConsumer.accept(null); undertowService.get().unregisterServer(this); } @Override public Server getValue() { return this; } protected void registerListener(ListenerService listener) { listeners.add(listener); if (!listener.isSecure()) { SocketBinding binding = listener.getBinding().get(); SocketBinding redirectBinding = listener.getRedirectSocket() != null ? listener.getRedirectSocket().get() : null; if (redirectBinding!=null) { securePortMappings.put(binding.getAbsolutePort(), redirectBinding.getAbsolutePort()); }else{ securePortMappings.put(binding.getAbsolutePort(), -1); } } } protected void unregisterListener(ListenerService listener) { listeners.remove(listener); if (!listener.isSecure()) { SocketBinding binding = listener.getBinding().get(); securePortMappings.remove(binding.getAbsolutePort()); } } protected void registerHost(final Host host) { hosts.add(host); for (String hostName : host.getAllAliases()) { virtualHostHandler.addHost(hostName, host.getRootHandler()); } if (host.getName().equals(getDefaultHost())) { virtualHostHandler.setDefaultHandler(host.getRootHandler()); } } protected void unregisterHost(Host host) { for (String hostName : host.getAllAliases()) { virtualHostHandler.removeHost(hostName); hosts.remove(host); } if (host.getName().equals(getDefaultHost())) { virtualHostHandler.setDefaultHandler(ResponseCodeHandler.HANDLE_404); } } public int lookupSecurePort(final int unsecurePort) { return securePortMappings.get(unsecurePort); } public ServletContainerService getServletContainer() { return servletContainer.get(); } protected HttpHandler getRoot() { return root; } UndertowService getUndertowService() { return undertowService.get(); } public String getName() { return name; } public String getDefaultHost() { return defaultHost; } public Set<Host> getHosts() { return Collections.unmodifiableSet(hosts); } public List<UndertowListener> getListeners() { return (List)listeners; } public String getRoute() { final UndertowService service = this.undertowService.get(); final String defaultServerRoute = service.getInstanceId(); if (service.isObfuscateSessionRoute()) { try { final MessageDigest md = MessageDigest.getInstance("MD5"); // salt md.update(this.name.getBytes(UTF_8)); // encode final byte[] digestedBytes = md.digest(defaultServerRoute.getBytes(UTF_8)); final Base64.Encoder encoder = Base64.getUrlEncoder().withoutPadding(); // = is not allowed in V0 Cookie final String encodedRoute = new String(encoder.encode(digestedBytes), UTF_8); UndertowLogger.ROOT_LOGGER.obfuscatedSessionRoute(encodedRoute, defaultServerRoute); return encodedRoute; } catch (NoSuchAlgorithmException e) { UndertowLogger.ROOT_LOGGER.unableToObfuscateSessionRoute(defaultServerRoute, e); } } return this.name.equals(service.getDefaultServer()) ? defaultServerRoute : String.join("-", defaultServerRoute, this.name); } private final class DefaultHostHandler implements HttpHandler { private final HttpHandler next; private DefaultHostHandler(HttpHandler next) { this.next = next; } @Override public void handleRequest(HttpServerExchange exchange) throws Exception { if(!exchange.getRequestHeaders().contains(Headers.HOST)) { exchange.getRequestHeaders().put(Headers.HOST, defaultHost + ":" + exchange.getDestinationAddress().getPort()); } next.handleRequest(exchange); } } }
8,178
37.04186
131
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/BufferCacheService.java
/* * 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<DirectBufferCache> { 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; } }
2,392
35.257576
112
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/HttpsListenerService.java
/* * 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 java.util.function.Consumer; import java.util.function.Supplier; import javax.net.ssl.SSLContext; import io.undertow.UndertowOptions; import io.undertow.connector.ByteBufferPool; import io.undertow.protocols.ssl.UndertowXnioSsl; import io.undertow.server.OpenListener; import io.undertow.server.protocol.http.AlpnOpenListener; import io.undertow.server.protocol.http.HttpOpenListener; import io.undertow.server.protocol.http2.Http2OpenListener; import org.jboss.as.controller.PathAddress; import org.jboss.as.network.NetworkUtils; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.security.ssl.CipherSuiteSelector; import org.xnio.ChannelListener; import org.xnio.IoUtils; import org.xnio.Option; import org.xnio.OptionMap; import org.xnio.OptionMap.Builder; import org.xnio.Options; import org.xnio.Sequence; import org.xnio.StreamConnection; import org.xnio.XnioWorker; import org.xnio.channels.AcceptingChannel; import org.xnio.ssl.SslConnection; import org.xnio.ssl.XnioSsl; /** * An extension of {@see HttpListenerService} to add SSL. * * @author <a href="mailto:[email protected]">Darran Lofthouse</a> * @author Tomaz Cerar * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class HttpsListenerService extends HttpListenerService { private Supplier<SSLContext> sslContextSupplier; private volatile AcceptingChannel<SslConnection> sslServer; static final String PROTOCOL = "https"; private final String cipherSuites; private final boolean proxyProtocol; public HttpsListenerService(final Consumer<ListenerService> serviceConsumer, final PathAddress address, String serverName, OptionMap listenerOptions, String cipherSuites, OptionMap socketOptions, boolean proxyProtocol) { this(serviceConsumer, address, serverName, listenerOptions, cipherSuites, socketOptions, false, false, proxyProtocol); } HttpsListenerService(final Consumer<ListenerService> serviceConsumer, final PathAddress address, String serverName, OptionMap listenerOptions, String cipherSuites, OptionMap socketOptions, boolean certificateForwarding, boolean proxyAddressForwarding, boolean proxyProtocol) { super(serviceConsumer, address, serverName, listenerOptions, socketOptions, certificateForwarding, proxyAddressForwarding, proxyProtocol); this.cipherSuites = cipherSuites; this.proxyProtocol = proxyProtocol; } void setSSLContextSupplier(Supplier<SSLContext> sslContextSupplier) { this.sslContextSupplier = sslContextSupplier; } @Override protected UndertowXnioSsl getSsl() { SSLContext sslContext = sslContextSupplier.get(); OptionMap combined = getSSLOptions(sslContext); return new UndertowXnioSsl(worker.get().getXnio(), combined, sslContext); } protected OptionMap getSSLOptions(SSLContext sslContext) { Builder builder = OptionMap.builder().addAll(commonOptions); builder.addAll(socketOptions); builder.set(Options.USE_DIRECT_BUFFERS, true); if (cipherSuites != null) { String[] cipherList = CipherSuiteSelector.fromString(cipherSuites).evaluate(sslContext.getSupportedSSLParameters().getCipherSuites()); builder.setSequence((Option<Sequence<String>>) HttpsListenerResourceDefinition.ENABLED_CIPHER_SUITES.getOption(), cipherList); } return builder.getMap(); } @Override protected OpenListener createOpenListener() { if(listenerOptions.get(UndertowOptions.ENABLE_HTTP2, false)) { try { return createAlpnOpenListener(); } catch (Throwable e) { UndertowLogger.ROOT_LOGGER.alpnNotFound(getName()); UndertowLogger.ROOT_LOGGER.debug("Exception creating ALPN listener", e); return super.createOpenListener(); } } else { return super.createOpenListener(); } } private OpenListener createAlpnOpenListener() { OptionMap undertowOptions = OptionMap.builder().addAll(commonOptions).addAll(listenerOptions).set(UndertowOptions.ENABLE_CONNECTOR_STATISTICS, getUndertowService().isStatisticsEnabled()).getMap(); ByteBufferPool bufferPool = getBufferPool().get(); HttpOpenListener http = new HttpOpenListener(bufferPool, undertowOptions); AlpnOpenListener alpn = new AlpnOpenListener(bufferPool, undertowOptions, http); if(listenerOptions.get(UndertowOptions.ENABLE_HTTP2, false)) { Http2OpenListener http2 = new Http2OpenListener(bufferPool, undertowOptions, "h2"); alpn.addProtocol(Http2OpenListener.HTTP2, http2, 10); Http2OpenListener http2_14 = new Http2OpenListener(bufferPool, undertowOptions, "h2-14"); alpn.addProtocol(Http2OpenListener.HTTP2_14, http2_14, 9); } return alpn; } @Override protected void startListening(XnioWorker worker, InetSocketAddress socketAddress, ChannelListener<AcceptingChannel<StreamConnection>> acceptListener) throws IOException { if(proxyProtocol) { sslServer = worker.createStreamConnectionServer(socketAddress, (ChannelListener) acceptListener, getSSLOptions(sslContextSupplier.get())); } else { XnioSsl ssl = getSsl(); sslServer = ssl.createSslConnectionServer(worker, socketAddress, (ChannelListener) acceptListener, getSSLOptions(sslContextSupplier.get())); } sslServer.resumeAccepts(); final InetSocketAddress boundAddress = sslServer.getLocalAddress(InetSocketAddress.class); UndertowLogger.ROOT_LOGGER.listenerStarted("HTTPS", getName(), NetworkUtils.formatIPAddressForURI(boundAddress.getAddress()), boundAddress.getPort()); } @Override public boolean isSecure() { return true; } @Override protected void stopListening() { final InetSocketAddress boundAddress = sslServer.getLocalAddress(InetSocketAddress.class); sslServer.suspendAccepts(); UndertowLogger.ROOT_LOGGER.listenerSuspend("HTTPS", getName()); IoUtils.safeClose(sslServer); sslServer = null; UndertowLogger.ROOT_LOGGER.listenerStopped("HTTPS", getName(), NetworkUtils.formatIPAddressForURI(boundAddress.getAddress()), boundAddress.getPort()); httpListenerRegistry.get().removeListener(getName()); } @Override public String getProtocol() { return PROTOCOL; } }
7,631
42.862069
280
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/DefaultResponseCodeHandler.java
/* * 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; } }
2,259
32.235294
91
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/ServletContainerAdd.java
/* * 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.connector.ByteBufferPool; import io.undertow.server.handlers.cache.DirectBufferCache; import io.undertow.servlet.api.CrawlerSessionManagerConfig; import io.undertow.servlet.api.ServletContainer; import io.undertow.servlet.api.ServletStackTraces; import io.undertow.servlet.api.SessionPersistenceManager; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.CapabilityServiceTarget; import org.jboss.as.controller.ExpressionResolver; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.registry.Resource; import org.jboss.dmr.ModelNode; import org.jboss.dmr.Property; import org.jboss.msc.Service; import org.jboss.msc.service.ServiceController; import org.xnio.XnioWorker; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Supplier; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class ServletContainerAdd extends AbstractBoottimeAddStepHandler { ServletContainerAdd() { super(ServletContainerDefinition.ATTRIBUTES); } @Override protected void performBoottime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { installRuntimeServices(context.getCapabilityServiceTarget(), context, context.getCurrentAddress(), Resource.Tools.readModel(resource)); } static void installRuntimeServices(CapabilityServiceTarget target, ExpressionResolver resolver, PathAddress address, ModelNode model) throws OperationFailedException { final CookieConfig sessionCookieConfig = SessionCookieDefinition.getConfig(resolver, model.get(SessionCookieDefinition.PATH_ELEMENT.getKeyValuePair())); final CookieConfig affinityCookieConfig = AffinityCookieDefinition.getConfig(resolver, model.get(AffinityCookieDefinition.PATH_ELEMENT.getKeyValuePair())); final CrawlerSessionManagerConfig crawlerSessionManagerConfig = CrawlerSessionManagementDefinition.getConfig(resolver, model.get(CrawlerSessionManagementDefinition.PATH_ELEMENT.getKeyValuePair())); final boolean persistentSessions = PersistentSessionsDefinition.isEnabled(model.get(PersistentSessionsDefinition.PATH_ELEMENT.getKeyValuePair())); final boolean allowNonStandardWrappers = ServletContainerDefinition.ALLOW_NON_STANDARD_WRAPPERS.resolveModelAttribute(resolver, model).asBoolean(); final boolean proactiveAuth = ServletContainerDefinition.PROACTIVE_AUTHENTICATION.resolveModelAttribute(resolver, model).asBoolean(); final String bufferCache = ServletContainerDefinition.DEFAULT_BUFFER_CACHE.resolveModelAttribute(resolver, model).asString(); final boolean disableFileWatchService = ServletContainerDefinition.DISABLE_FILE_WATCH_SERVICE.resolveModelAttribute(resolver, model).asBoolean(); final boolean disableSessionIdReususe = ServletContainerDefinition.DISABLE_SESSION_ID_REUSE.resolveModelAttribute(resolver, model).asBoolean(); JSPConfig jspConfig = JspDefinition.getConfig(resolver, model.get(JspDefinition.PATH_ELEMENT.getKeyValuePair())); final String stackTracesString = ServletContainerDefinition.STACK_TRACE_ON_ERROR.resolveModelAttribute(resolver, model).asString(); final ModelNode defaultEncodingValue = ServletContainerDefinition.DEFAULT_ENCODING.resolveModelAttribute(resolver, model); final String defaultEncoding = defaultEncodingValue.isDefined()? defaultEncodingValue.asString() : null; final boolean useListenerEncoding = ServletContainerDefinition.USE_LISTENER_ENCODING.resolveModelAttribute(resolver, model).asBoolean(); final boolean ignoreFlush = ServletContainerDefinition.IGNORE_FLUSH.resolveModelAttribute(resolver, model).asBoolean(); final boolean eagerFilterInit = ServletContainerDefinition.EAGER_FILTER_INIT.resolveModelAttribute(resolver, model).asBoolean(); final boolean disableCachingForSecuredPages = ServletContainerDefinition.DISABLE_CACHING_FOR_SECURED_PAGES.resolveModelAttribute(resolver, model).asBoolean(); final int sessionIdLength = ServletContainerDefinition.SESSION_ID_LENGTH.resolveModelAttribute(resolver, model).asInt(); final int fileCacheMetadataSize = ServletContainerDefinition.FILE_CACHE_METADATA_SIZE.resolveModelAttribute(resolver, model).asInt(); final int fileCacheMaxFileSize = ServletContainerDefinition.FILE_CACHE_MAX_FILE_SIZE.resolveModelAttribute(resolver, model).asInt(); final ModelNode fileCacheTtlNode = ServletContainerDefinition.FILE_CACHE_TIME_TO_LIVE.resolveModelAttribute(resolver, model); final Integer fileCacheTimeToLive = fileCacheTtlNode.isDefined() ? fileCacheTtlNode.asInt() : null; final int defaultCookieVersion = ServletContainerDefinition.DEFAULT_COOKIE_VERSION.resolveModelAttribute(resolver, model).asInt(); final boolean preservePathOnForward = ServletContainerDefinition.PRESERVE_PATH_ON_FORWARD.resolveModelAttribute(resolver, model).asBoolean(); boolean orphanSessionAllowed = ServletContainerDefinition.ORPHAN_SESSION_ALLOWED.resolveModelAttribute(resolver, model).asBoolean(); Boolean directoryListingEnabled = ServletContainerDefinition.DIRECTORY_LISTING.resolveModelAttribute(resolver, model).asBooleanOrNull(); Integer maxSessions = ServletContainerDefinition.MAX_SESSIONS.resolveModelAttribute(resolver, model).asIntOrNull(); final int sessionTimeout = ServletContainerDefinition.DEFAULT_SESSION_TIMEOUT.resolveModelAttribute(resolver, model).asInt(); WebsocketsDefinition.WebSocketInfo webSocketInfo = WebsocketsDefinition.getConfig(resolver, model.get(WebsocketsDefinition.PATH_ELEMENT.getKeyValuePair())); Map<String, String> mimeMappings = resolveMimeMappings(resolver, model); List<String> welcomeFiles = resolveWelcomeFiles(model); final CapabilityServiceBuilder<?> builder = target.addCapability(ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY); final Supplier<SessionPersistenceManager> sessionPersistenceManager = persistentSessions ? builder.requires(AbstractPersistentSessionManager.SERVICE_NAME) : null; final Supplier<DirectBufferCache> directBufferCache = bufferCache != null ? builder.requires(BufferCacheService.SERVICE_NAME.append(bufferCache)) : null; final Supplier<ByteBufferPool> byteBufferPool = webSocketInfo != null ? builder.requiresCapability(Capabilities.CAPABILITY_BYTE_BUFFER_POOL, ByteBufferPool.class, webSocketInfo.getBufferPool()) : null; final Supplier<XnioWorker> xnioWorker = webSocketInfo != null ? builder.requiresCapability(Capabilities.REF_IO_WORKER, XnioWorker.class, webSocketInfo.getWorker()) : null; ServletStackTraces traces = ServletStackTraces.valueOf(stackTracesString.toUpperCase().replace('-', '_')); ServletContainer container = ServletContainer.Factory.newInstance(); ServletContainerService service = new ServletContainerService() { @Override public ServletContainer getServletContainer() { return container; } @Override public boolean isAllowNonStandardWrappers() { return allowNonStandardWrappers; } @Override public JSPConfig getJspConfig() { return jspConfig; } @Override public ServletStackTraces getStackTraces() { return traces; } @Override public CookieConfig getSessionCookieConfig() { return sessionCookieConfig; } @Override public CookieConfig getAffinityCookieConfig() { return affinityCookieConfig; } @Override public DirectBufferCache getBufferCache() { return (directBufferCache != null) ? directBufferCache.get() : null; } @Override public boolean isDisableCachingForSecuredPages() { return disableCachingForSecuredPages; } @Override public boolean isDispatchWebsocketInvocationToWorker() { return (webSocketInfo != null) && webSocketInfo.isDispatchToWorker(); } @Override public boolean isPerMessageDeflate() { return (webSocketInfo != null) && webSocketInfo.isPerMessageDeflate(); } @Override public int getDeflaterLevel() { return (webSocketInfo != null) ? webSocketInfo.getDeflaterLevel() : -1; } @Override public boolean isWebsocketsEnabled() { return webSocketInfo != null; } @Override public boolean isDisableSessionIdReuse() { return disableSessionIdReususe; } @Override public SessionPersistenceManager getSessionPersistenceManager() { return (sessionPersistenceManager != null) ? sessionPersistenceManager.get() : null; } @Override public XnioWorker getWebsocketsWorker() { return (xnioWorker != null) ? xnioWorker.get() : null; } @Override public ByteBufferPool getWebsocketsBufferPool() { return (byteBufferPool != null) ? byteBufferPool.get() : null; } @Override public String getDefaultEncoding() { return defaultEncoding; } @Override public boolean isUseListenerEncoding() { return useListenerEncoding; } @Override public boolean isIgnoreFlush() { return ignoreFlush; } @Override public boolean isEagerFilterInit() { return eagerFilterInit; } @Override public int getDefaultSessionTimeout() { return sessionTimeout; } @Override public Map<String, String> getMimeMappings() { return mimeMappings; } @Override public List<String> getWelcomeFiles() { return welcomeFiles; } @Override public Boolean getDirectoryListingEnabled() { return directoryListingEnabled; } @Override public boolean isProactiveAuth() { return proactiveAuth; } @Override public int getSessionIdLength() { return sessionIdLength; } @Override public Integer getMaxSessions() { return maxSessions; } @Override public boolean isDisableFileWatchService() { return disableFileWatchService; } @Override public CrawlerSessionManagerConfig getCrawlerSessionManagerConfig() { return crawlerSessionManagerConfig; } @Override public int getFileCacheMetadataSize() { return fileCacheMetadataSize; } @Override public int getFileCacheMaxFileSize() { return fileCacheMaxFileSize; } @Override public Integer getFileCacheTimeToLive() { return fileCacheTimeToLive; } @Override public int getDefaultCookieVersion() { return defaultCookieVersion; } @Override public boolean isPreservePathOnForward() { return preservePathOnForward; } @Override public boolean isOrphanSessionAllowed() { return orphanSessionAllowed; } }; builder.setInstance(Service.newInstance(builder.provides(ServletContainerDefinition.SERVLET_CONTAINER_CAPABILITY, UndertowService.SERVLET_CONTAINER.append(address.getLastElement().getValue())), service)); builder.setInitialMode(ServiceController.Mode.ON_DEMAND); builder.install(); } private static Map<String, String> resolveMimeMappings(ExpressionResolver resolver, ModelNode model) throws OperationFailedException { if (!model.hasDefined(Constants.MIME_MAPPING)) return Map.of(); List<Property> properties = model.get(Constants.MIME_MAPPING).asPropertyList(); if (properties.size() == 1) { Map.Entry<String, String> entry = resolveMimeMapping(resolver, properties.get(0)); return Map.of(entry.getKey(), entry.getValue()); } Map<String, String> result = new HashMap<>(); for (Property property : properties) { Map.Entry<String, String> entry = resolveMimeMapping(resolver, property); result.put(entry.getKey(), entry.getValue()); } return Collections.unmodifiableMap(result); } private static Map.Entry<String, String> resolveMimeMapping(ExpressionResolver resolver, Property property) throws OperationFailedException { return Map.entry(property.getName(), MimeMappingDefinition.VALUE.resolveModelAttribute(resolver, property.getValue()).asString()); } private static List<String> resolveWelcomeFiles(ModelNode model) { if (!model.hasDefined(Constants.WELCOME_FILE)) return List.of(); List<Property> properties = model.get(Constants.WELCOME_FILE).asPropertyList(); if (properties.size() == 1) { return List.of(properties.get(0).getName()); } List<String> result = new ArrayList<>(properties.size()); for (Property property : properties) { result.add(property.getName()); } return Collections.unmodifiableList(result); } }
15,398
45.948171
212
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/LocationAdd.java
/* * 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 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.dmr.ModelNode; import java.util.function.Consumer; import java.util.function.Supplier; /** * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2013 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> */ final class LocationAdd extends AbstractAddStepHandler { static LocationAdd INSTANCE = new LocationAdd(); private LocationAdd() { super(LocationDefinition.HANDLER); } @Override protected void performRuntime(OperationContext context, ModelNode operation, ModelNode model) throws OperationFailedException { final PathAddress hostAddress = context.getCurrentAddress().getParent(); final PathAddress serverAddress = hostAddress.getParent(); final String name = context.getCurrentAddressValue(); final String handler = LocationDefinition.HANDLER.resolveModelAttribute(context, model).asString(); final String serverName = serverAddress.getLastElement().getValue(); final String hostName = hostAddress.getLastElement().getValue(); final CapabilityServiceBuilder<?> sb = context.getCapabilityServiceTarget().addCapability(LocationDefinition.LOCATION_CAPABILITY); final Consumer<LocationService> sConsumer = sb.provides(LocationDefinition.LOCATION_CAPABILITY, UndertowService.locationServiceName(serverName, hostName, name)); final Supplier<HttpHandler> hhSupplier = sb.requiresCapability(Capabilities.CAPABILITY_HANDLER, HttpHandler.class, handler); final Supplier<Host> hSupplier = sb.requiresCapability(Capabilities.CAPABILITY_HOST, Host.class, serverName, hostName); sb.setInstance(new LocationService(sConsumer, hhSupplier, hSupplier, name)); sb.install(); } }
3,128
47.890625
169
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/BufferCacheAdd.java
/* * 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 * @author <a href="mailto:[email protected]">Richard Opalka</a> */ 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.ATTRIBUTES) { 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(); final int bufferSize = BufferCacheDefinition.BUFFER_SIZE.resolveModelAttribute(context, model).asInt(); final int buffersPerRegions = BufferCacheDefinition.BUFFERS_PER_REGION.resolveModelAttribute(context, model).asInt(); final 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)).setInstance(service) .setInitialMode(ServiceController.Mode.ON_DEMAND).install(); } }
3,055
44.61194
135
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/UndertowSubsystemAdd.java
/* * 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.EnumSet; import java.util.function.Consumer; import java.util.function.Predicate; import org.jboss.as.controller.AbstractBoottimeAddStepHandler; import org.jboss.as.controller.CapabilityServiceBuilder; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.registry.Resource; import org.jboss.as.server.AbstractDeploymentChainStep; import org.jboss.as.server.DeploymentProcessorTarget; import org.jboss.as.server.deployment.Phase; import org.jboss.as.server.deployment.jbossallxml.JBossAllSchema; import org.jboss.as.server.deployment.jbossallxml.JBossAllXmlParserRegisteringProcessor; import org.jboss.as.web.common.SharedTldsMetaDataBuilder; import org.jboss.as.web.session.SharedSessionManagerConfig; import org.jboss.dmr.ModelNode; import org.wildfly.extension.undertow.deployment.DefaultDeploymentMappingProvider; import org.wildfly.extension.undertow.deployment.DefaultSecurityDomainProcessor; import org.wildfly.extension.undertow.deployment.DeploymentRootExplodedMountProcessor; import org.wildfly.extension.undertow.deployment.EarContextRootProcessor; import org.wildfly.extension.undertow.deployment.ExternalTldParsingDeploymentProcessor; import org.wildfly.extension.undertow.deployment.JBossWebParsingDeploymentProcessor; import org.wildfly.extension.undertow.deployment.SecurityDomainResolvingProcessor; import org.wildfly.extension.undertow.deployment.ServletContainerInitializerDeploymentProcessor; import org.wildfly.extension.undertow.deployment.SharedSessionManagerDeploymentProcessor; import org.wildfly.extension.undertow.deployment.TldParsingDeploymentProcessor; import org.wildfly.extension.undertow.deployment.UndertowDependencyProcessor; import org.wildfly.extension.undertow.deployment.UndertowDeploymentProcessor; import org.wildfly.extension.undertow.deployment.UndertowHandlersDeploymentProcessor; import org.wildfly.extension.undertow.deployment.UndertowJSRWebSocketDeploymentProcessor; import org.wildfly.extension.undertow.deployment.UndertowServletContainerDependencyProcessor; import org.wildfly.extension.undertow.deployment.WarAnnotationDeploymentProcessor; import org.wildfly.extension.undertow.deployment.WarDeploymentInitializingProcessor; import org.wildfly.extension.undertow.deployment.WarMetaDataProcessor; import org.wildfly.extension.undertow.deployment.WarStructureDeploymentProcessor; import org.wildfly.extension.undertow.deployment.WebFragmentParsingDeploymentProcessor; import org.wildfly.extension.undertow.deployment.WebJBossAllParser; import org.wildfly.extension.undertow.deployment.WebParsingDeploymentProcessor; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.session.SharedSessionConfigSchema; import static org.wildfly.extension.undertow.UndertowRootDefinition.HTTP_INVOKER_RUNTIME_CAPABILITY; /** * Handler responsible for adding the subsystem resource to the model * * @author <a href="mailto:[email protected]">Tomaz Cerar</a> (c) 2012 Red Hat Inc. * @author <a href="mailto:[email protected]">Richard Opalka</a> * @author Flavia Rainone */ class UndertowSubsystemAdd extends AbstractBoottimeAddStepHandler { private final Predicate<String> knownSecurityDomain; UndertowSubsystemAdd(Predicate<String> knownSecurityDomain) { super(UndertowRootDefinition.ATTRIBUTES); this.knownSecurityDomain = knownSecurityDomain; } /** * {@inheritDoc} */ @Override protected void performBoottime(OperationContext context, ModelNode operation, Resource resource) throws OperationFailedException { try { Class.forName("org.apache.jasper.compiler.JspRuntimeContext", true, this.getClass().getClassLoader()); } catch (ClassNotFoundException e) { UndertowLogger.ROOT_LOGGER.couldNotInitJsp(e); } final ModelNode model = resource.getModel(); final String defaultVirtualHost = UndertowRootDefinition.DEFAULT_VIRTUAL_HOST.resolveModelAttribute(context, model).asString(); final String defaultContainer = UndertowRootDefinition.DEFAULT_SERVLET_CONTAINER.resolveModelAttribute(context, model).asString(); final String defaultServer = UndertowRootDefinition.DEFAULT_SERVER.resolveModelAttribute(context, model).asString(); final boolean stats = UndertowRootDefinition.STATISTICS_ENABLED.resolveModelAttribute(context, model).asBoolean(); final String defaultSecurityDomain = UndertowRootDefinition.DEFAULT_SECURITY_DOMAIN.resolveModelAttribute(context, model).asString(); final ModelNode instanceIdModel = UndertowRootDefinition.INSTANCE_ID.resolveModelAttribute(context, model); final String instanceId = instanceIdModel.isDefined() ? instanceIdModel.asString() : null; final boolean obfuscateSessionRoute = UndertowRootDefinition.OBFUSCATE_SESSION_ROUTE.resolveModelAttribute(context, model).asBoolean(); DefaultDeploymentMappingProvider.instance().clear();//we clear provider on system boot, as on reload it could cause issues. final CapabilityServiceBuilder<?> csb = context.getCapabilityServiceTarget().addCapability(UndertowRootDefinition.UNDERTOW_CAPABILITY); final Consumer<UndertowService> usConsumer = csb.provides(UndertowRootDefinition.UNDERTOW_CAPABILITY, UndertowService.UNDERTOW); csb.setInstance(new UndertowService(usConsumer, defaultContainer, defaultServer, defaultVirtualHost, instanceId, obfuscateSessionRoute, stats)); csb.install(); context.addStep(new AbstractDeploymentChainStep() { @Override protected void execute(DeploymentProcessorTarget processorTarget) { final SharedTldsMetaDataBuilder sharedTldsBuilder = new SharedTldsMetaDataBuilder(model.clone()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_EXPLODED_MOUNT, new DeploymentRootExplodedMountProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_REGISTER_JBOSS_ALL_UNDERTOW_SHARED_SESSION, JBossAllSchema.createDeploymentUnitProcessor(EnumSet.allOf(SharedSessionConfigSchema.class), SharedSessionManagerConfig.ATTACHMENT_KEY)); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_REGISTER_JBOSS_ALL_WEB, new JBossAllXmlParserRegisteringProcessor<>(WebJBossAllParser.ROOT_ELEMENT, WebJBossAllParser.ATTACHMENT_KEY, new WebJBossAllParser())); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_WAR_DEPLOYMENT_INIT, new WarDeploymentInitializingProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.STRUCTURE, Phase.STRUCTURE_WAR, new WarStructureDeploymentProcessor(sharedTldsBuilder)); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WEB_DEPLOYMENT, new WebParsingDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WEB_DEPLOYMENT_FRAGMENT, new WebFragmentParsingDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_JBOSS_WEB_DEPLOYMENT, new JBossWebParsingDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_ANNOTATION_WAR, new WarAnnotationDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_EAR_CONTEXT_ROOT, new EarContextRootProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WEB_MERGE_METADATA, new WarMetaDataProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_TLD_DEPLOYMENT, new TldParsingDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_WEB_COMPONENTS, new org.wildfly.extension.undertow.deployment.WebComponentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.PARSE, Phase.PARSE_UNDERTOW_DEFAULT_SECURITY_DOMAIN, new DefaultSecurityDomainProcessor(defaultSecurityDomain)); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_WAR_MODULE, new UndertowDependencyProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_UNDERTOW_WEBSOCKETS, new UndertowJSRWebSocketDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_UNDERTOW_HANDLERS, new UndertowHandlersDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_EXTERNAL_TAGLIB, new ExternalTldParsingDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.POST_MODULE, Phase.POST_MODULE_UNDERTOW_SERVLET_CONTAINER_DEPENDENCY, new UndertowServletContainerDependencyProcessor(defaultContainer)); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_SHARED_SESSION_MANAGER, new SharedSessionManagerDeploymentProcessor(defaultServer)); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_SERVLET_INIT_DEPLOYMENT, new ServletContainerInitializerDeploymentProcessor()); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_WEB_RESOLVE_SECURITY_DOMAIN, new SecurityDomainResolvingProcessor(defaultSecurityDomain, knownSecurityDomain)); processorTarget.addDeploymentProcessor(UndertowExtension.SUBSYSTEM_NAME, Phase.INSTALL, Phase.INSTALL_WAR_DEPLOYMENT, new UndertowDeploymentProcessor(defaultVirtualHost, defaultContainer, defaultServer, knownSecurityDomain)); } }, OperationContext.Stage.RUNTIME); context.getCapabilityServiceTarget() .addCapability(HTTP_INVOKER_RUNTIME_CAPABILITY) .setInstance(new RemoteHttpInvokerService()) .install(); } }
11,796
70.932927
303
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/security/jacc/WarJACCService.java
/* * 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.security.jacc; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import jakarta.security.jacc.PolicyConfiguration; import jakarta.security.jacc.PolicyContextException; import jakarta.security.jacc.WebResourcePermission; import jakarta.security.jacc.WebRoleRefPermission; import jakarta.security.jacc.WebUserDataPermission; import org.jboss.as.ee.security.JaccService; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefsMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossServletsMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.SecurityConstraintMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.ServletSecurityMetaData; import org.jboss.metadata.web.spec.UserDataConstraintMetaData; import org.jboss.metadata.web.spec.WebResourceCollectionMetaData; import org.jboss.metadata.web.spec.WebResourceCollectionsMetaData; /** * A service that creates Jakarta Authorization permissions for a web deployment * @author [email protected] * @author [email protected] * @author <a href="mailto:[email protected]">Marcus Moyses</a> */ public class WarJACCService extends JaccService<WarMetaData> { /** A prefix pattern "/prefix/*" */ private static final int PREFIX = 1; /** An extension pattern "*.ext" */ private static final int EXTENSION = 2; /** The "/" default pattern */ private static final int DEFAULT = 3; /** A prefix pattern "/prefix/*" */ private static final int EXACT = 4; private static final String ANY_AUTHENTICATED_USER_ROLE = "**"; public WarJACCService(String contextId, WarMetaData metaData, Boolean standalone) { super(contextId, metaData, standalone); } /** {@inheritDoc} */ @Override public void createPermissions(WarMetaData metaData, PolicyConfiguration pc) throws PolicyContextException { JBossWebMetaData jbossWebMetaData = metaData.getMergedJBossWebMetaData(); HashMap<String, PatternInfo> patternMap = qualifyURLPatterns(jbossWebMetaData); List<SecurityConstraintMetaData> secConstraints = jbossWebMetaData.getSecurityConstraints(); if (secConstraints != null) { for (SecurityConstraintMetaData secConstraint : secConstraints) { WebResourceCollectionsMetaData resourceCollectionsMetaData = secConstraint.getResourceCollections(); UserDataConstraintMetaData userDataConstraintMetaData = secConstraint.getUserDataConstraint(); if (resourceCollectionsMetaData != null) { if (secConstraint.isExcluded() || secConstraint.isUnchecked()) { // Process the permissions for the excluded/unchecked resources for (WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData) { List<String> httpMethods = new ArrayList<>(resourceCollectionMetaData.getHttpMethods()); List<String> ommisions = resourceCollectionMetaData.getHttpMethodOmissions(); if(httpMethods.isEmpty() && !ommisions.isEmpty()) { httpMethods.addAll(WebResourceCollectionMetaData.ALL_HTTP_METHODS); httpMethods.removeAll(ommisions); } List<String> urlPatterns = resourceCollectionMetaData.getUrlPatterns(); for (String urlPattern : urlPatterns) { PatternInfo info = patternMap.get(urlPattern); info.descriptor=true; // Add the excluded methods if (secConstraint.isExcluded()) { info.addExcludedMethods(httpMethods); } // SECURITY-63: Missing auth-constraint needs unchecked policy if (secConstraint.isUnchecked() && httpMethods.isEmpty()) { info.isMissingAuthConstraint = true; } else { info.missingAuthConstraintMethods.addAll(httpMethods); } } } } else { // Process the permission for the resources x roles for (WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData) { List<String> httpMethods = new ArrayList<>(resourceCollectionMetaData.getHttpMethods()); List<String> methodOmissions = resourceCollectionMetaData.getHttpMethodOmissions(); if(httpMethods.isEmpty() && !methodOmissions.isEmpty()) { httpMethods.addAll(WebResourceCollectionMetaData.ALL_HTTP_METHODS); httpMethods.removeAll(methodOmissions); } List<String> urlPatterns = resourceCollectionMetaData.getUrlPatterns(); for (String urlPattern : urlPatterns) { // Get the qualified url pattern PatternInfo info = patternMap.get(urlPattern); info.descriptor=true; HashSet<String> mappedRoles = new HashSet<String>(); secConstraint.getAuthConstraint().getRoleNames(); List<String> authRoles = secConstraint.getAuthConstraint().getRoleNames(); for (String role : authRoles) { if ("*".equals(role)) { // The wildcard ref maps to all declared security-role names mappedRoles.addAll(jbossWebMetaData.getSecurityRoleNames()); } else { mappedRoles.add(role); } } info.addRoles(mappedRoles, httpMethods); // Add the transport to methods if (userDataConstraintMetaData != null && userDataConstraintMetaData.getTransportGuarantee() != null) info.addTransport(userDataConstraintMetaData.getTransportGuarantee().name(), httpMethods); } } } } } } JBossServletsMetaData servlets = jbossWebMetaData.getServlets(); List<ServletMappingMetaData> mappings = jbossWebMetaData.getServletMappings(); if(servlets != null && mappings != null) { Map<String, List<String>> servletMappingMap = new HashMap<>(); for(ServletMappingMetaData mapping : mappings) { List<String> list = servletMappingMap.get(mapping.getServletName()); if(list == null) { servletMappingMap.put(mapping.getServletName(), list = new ArrayList<>()); } list.addAll(mapping.getUrlPatterns()); } if(!jbossWebMetaData.isMetadataComplete()) { for (JBossServletMetaData servlet : servlets) { ServletSecurityMetaData security = servlet.getServletSecurity(); if (security != null) { List<String> servletMappings = servletMappingMap.get(servlet.getServletName()); if (servletMappings != null) { if (security.getHttpMethodConstraints() != null) { for (HttpMethodConstraintMetaData s : security.getHttpMethodConstraints()) { if (s.getRolesAllowed() == null || s.getRolesAllowed().isEmpty()) { for (String urlPattern : servletMappings) { // Get the qualified url pattern PatternInfo info = patternMap.get(urlPattern); if (info.descriptor) { continue; } // Add the excluded methods if (s.getEmptyRoleSemantic() == null || s.getEmptyRoleSemantic() == EmptyRoleSemanticType.PERMIT) { info.missingAuthConstraintMethods.add(s.getMethod()); } else { info.addExcludedMethods(Collections.singletonList(s.getMethod())); } // Add the transport to methods if (s.getTransportGuarantee() != null) info.addTransport(s.getTransportGuarantee().name(), Collections.singletonList(s.getMethod())); } } else { for (String urlPattern : servletMappings) { // Get the qualified url pattern PatternInfo info = patternMap.get(urlPattern); if (info.descriptor) { continue; } HashSet<String> mappedRoles = new HashSet<String>(); List<String> authRoles = s.getRolesAllowed(); for (String role : authRoles) { if ("*".equals(role)) { // The wildcard ref maps to all declared security-role names mappedRoles.addAll(jbossWebMetaData.getSecurityRoleNames()); } else { mappedRoles.add(role); } } info.addRoles(mappedRoles, Collections.singletonList(s.getMethod())); // Add the transport to methods if (s.getTransportGuarantee() != null) info.addTransport(s.getTransportGuarantee().name(), Collections.singletonList(s.getMethod())); } } } } if (security.getRolesAllowed() == null || security.getRolesAllowed().isEmpty()) { for (String urlPattern : servletMappings) { // Get the qualified url pattern PatternInfo info = patternMap.get(urlPattern); if (info.descriptor) { continue; } // Add the excluded methods if (security.getEmptyRoleSemantic() == null || security.getEmptyRoleSemantic() == EmptyRoleSemanticType.PERMIT) { info.isMissingAuthConstraint = true; } else { Set<String> methods = new HashSet<>(WebResourceCollectionMetaData.ALL_HTTP_METHODS); if (security.getHttpMethodConstraints() != null) { for (HttpMethodConstraintMetaData method : security.getHttpMethodConstraints()) { methods.remove(method.getMethod()); } } info.addExcludedMethods(new ArrayList<>(methods)); } // Add the transport to methods if (security.getTransportGuarantee() != null) info.addTransport(security.getTransportGuarantee().name(), Collections.emptyList()); } } else { for (String urlPattern : servletMappings) { // Get the qualified url pattern PatternInfo info = patternMap.get(urlPattern); if (info.descriptor) { continue; } HashSet<String> mappedRoles = new HashSet<String>(); List<String> authRoles = security.getRolesAllowed(); for (String role : authRoles) { if ("*".equals(role)) { // The wildcard ref maps to all declared security-role names mappedRoles.addAll(jbossWebMetaData.getSecurityRoleNames()); } else { mappedRoles.add(role); } } info.addRoles(mappedRoles, Collections.emptyList()); // Add the transport to methods if (security.getTransportGuarantee() != null) info.addTransport(security.getTransportGuarantee().name(), Collections.emptyList()); } } } } } } } // Create the permissions for (PatternInfo info : patternMap.values()) { String qurl = info.getQualifiedPattern(); if (info.isOverridden) { continue; } // Create the excluded permissions String[] httpMethods = info.getExcludedMethods(); if (httpMethods != null) { // There were excluded security-constraints WebResourcePermission wrp = new WebResourcePermission(qurl, httpMethods); WebUserDataPermission wudp = new WebUserDataPermission(qurl, httpMethods, null); pc.addToExcludedPolicy(wrp); pc.addToExcludedPolicy(wudp); } // Create the role permissions Iterator<Map.Entry<String, Set<String>>> roles = info.getRoleMethods(); Set<String> seenMethods = new HashSet<>(); while (roles.hasNext()) { Map.Entry<String, Set<String>> roleMethods = roles.next(); String role = roleMethods.getKey(); Set<String> methods = roleMethods.getValue(); seenMethods.addAll(methods); httpMethods = methods.toArray(new String[methods.size()]); pc.addToRole(role, new WebResourcePermission(qurl, httpMethods)); } //there are totally 7 http methods from the jacc spec (See WebResourceCollectionMetaData.ALL_HTTP_METHOD_NAMES) final int NUMBER_OF_HTTP_METHODS = 7; // JACC 1.1: create !(httpmethods) in unchecked perms if(jbossWebMetaData.getDenyUncoveredHttpMethods() == null && seenMethods.size() != NUMBER_OF_HTTP_METHODS) { WebResourcePermission wrpUnchecked = seenMethods.isEmpty() ? new WebResourcePermission(qurl, (String) null) : new WebResourcePermission(qurl, "!" + getCommaSeparatedString(seenMethods.toArray(new String[seenMethods.size()]))); pc.addToUncheckedPolicy(wrpUnchecked); } if (jbossWebMetaData.getDenyUncoveredHttpMethods() == null) { // Create the unchecked permissions String[] missingHttpMethods = info.getMissingMethods(); int length = missingHttpMethods.length; roles = info.getRoleMethods(); if (length > 0 && !roles.hasNext()) { // Create the unchecked permissions WebResourcePermissions WebResourcePermission wrp = new WebResourcePermission(qurl, missingHttpMethods); pc.addToUncheckedPolicy(wrp); } else if (!roles.hasNext()) { pc.addToUncheckedPolicy(new WebResourcePermission(qurl, (String) null)); } // SECURITY-63: Missing auth-constraint needs unchecked policy if (info.isMissingAuthConstraint) { pc.addToUncheckedPolicy(new WebResourcePermission(qurl, (String) null)); } else if (!info.allMethods.containsAll(WebResourceCollectionMetaData.ALL_HTTP_METHODS)) { List<String> methods = new ArrayList<>(WebResourceCollectionMetaData.ALL_HTTP_METHODS); methods.removeAll(info.allMethods); pc.addToUncheckedPolicy(new WebResourcePermission(qurl, methods.toArray(new String[methods.size()]))); } if (!info.missingAuthConstraintMethods.isEmpty()) { pc.addToUncheckedPolicy(new WebResourcePermission(qurl, info.missingAuthConstraintMethods.toArray(new String[info.missingAuthConstraintMethods.size()]))); } } // Create the unchecked permissions WebUserDataPermissions Iterator<Map.Entry<String, Set<String>>> transportConstraints = info.getTransportMethods(); while (transportConstraints.hasNext()) { Map.Entry<String, Set<String>> transportMethods = transportConstraints.next(); String transport = transportMethods.getKey(); Set<String> methods = transportMethods.getValue(); httpMethods = new String[methods.size()]; methods.toArray(httpMethods); WebUserDataPermission wudp = new WebUserDataPermission(qurl, httpMethods, transport); pc.addToUncheckedPolicy(wudp); // If the transport is "NONE", then add an exclusive WebUserDataPermission // with the url pattern and null if ("NONE".equals(transport)) { WebUserDataPermission wudp1 = new WebUserDataPermission(qurl, null); pc.addToUncheckedPolicy(wudp1); } else { // JACC 1.1: Transport is CONFIDENTIAL/INTEGRAL, add a !(http methods) WebUserDataPermission wudpNonNull = new WebUserDataPermission(qurl, "!" + getCommaSeparatedString(httpMethods)); pc.addToUncheckedPolicy(wudpNonNull); } } } Set<String> declaredRoles = jbossWebMetaData.getSecurityRoleNames(); declaredRoles.add(ANY_AUTHENTICATED_USER_ROLE); /* * Create WebRoleRefPermissions for all servlet/security-role-refs along with all the cross product of servlets and * security-role elements that are not referenced via a security-role-ref as described in JACC section 3.1.3.2 */ JBossServletsMetaData servletsMetaData = jbossWebMetaData.getServlets(); for (JBossServletMetaData servletMetaData : servletsMetaData) { Set<String> unrefRoles = new HashSet<String>(declaredRoles); String servletName = servletMetaData.getName(); SecurityRoleRefsMetaData roleRefsMetaData = servletMetaData.getSecurityRoleRefs(); // Perform the unreferenced roles processing for every servlet name if (roleRefsMetaData != null) { for (SecurityRoleRefMetaData roleRefMetaData : roleRefsMetaData) { String roleRef = roleRefMetaData.getRoleLink(); String roleName = roleRefMetaData.getRoleName(); WebRoleRefPermission wrrp = new WebRoleRefPermission(servletName, roleName); pc.addToRole(roleRef, wrrp); // Remove the role from the unreferencedRoles unrefRoles.remove(roleName); } } // Spec 3.1.3.2: For each servlet element in the deployment descriptor // a WebRoleRefPermission must be added to each security-role of the // application whose name does not appear as the rolename // in a security-role-ref within the servlet element. for (String unrefRole : unrefRoles) { WebRoleRefPermission unrefP = new WebRoleRefPermission(servletName, unrefRole); pc.addToRole(unrefRole, unrefP); } } // JACC 1.1:Spec 3.1.3.2: For each security-role defined in the deployment descriptor, an // additional WebRoleRefPermission must be added to the corresponding role by // calling the addToRole method on the PolicyConfiguration object. The // name of all such permissions must be the empty string, and the actions of each // such permission must be the role-name of the corresponding role. for (String role : declaredRoles) { WebRoleRefPermission wrrep = new WebRoleRefPermission("", role); pc.addToRole(role, wrrep); } } static String getCommaSeparatedString(String[] str) { int len = str.length; Arrays.sort(str); StringBuilder buf = new StringBuilder(); for (int i = 0; i < len; i++) { if (i > 0) buf.append(","); buf.append(str[i]); } return buf.toString(); } /** * Determine the url-pattern type * * @param urlPattern - the raw url-pattern value * @return one of EXACT, EXTENSION, PREFIX, DEFAULT */ static int getPatternType(String urlPattern) { int type = EXACT; if (urlPattern.startsWith("*.")) type = EXTENSION; else if (urlPattern.startsWith("/") && urlPattern.endsWith("/*")) type = PREFIX; else if (urlPattern.equals("/")) type = DEFAULT; return type; } /** * Jakarta Authorization url pattern Qualified URL Pattern Names. * * The rules for qualifying a URL pattern are dependent on the rules for determining if one URL pattern matches another as * defined in Section 3.1.3.3, Servlet URL-Pattern Matching Rules, and are described as follows: - If the pattern is a path * prefix pattern, it must be qualified by every path-prefix pattern in the deployment descriptor matched by and different * from the pattern being qualified. The pattern must also be qualified by every exact pattern appearing in the deployment * descriptor that is matched by the pattern being qualified. - If the pattern is an extension pattern, it must be qualified * by every path-prefix pattern appearing in the deployment descriptor and every exact pattern in the deployment descriptor * that is matched by the pattern being qualified. - If the pattern is the default pattern, "/", it must be qualified by * every other pattern except the default pattern appearing in the deployment descriptor. - If the pattern is an exact * pattern, its qualified form must not contain any qualifying patterns. * * URL patterns are qualified by appending to their String representation, a colon separated representation of the list of * patterns that qualify the pattern. Duplicates must not be included in the list of qualifying patterns, and any qualifying * pattern matched by another qualifying pattern may5 be dropped from the list. * * Any pattern, qualified by a pattern that matches it, is overridden and made irrelevant (in the translation) by the * qualifying pattern. Specifically, all extension patterns and the default pattern are made irrelevant by the presence of * the path prefix pattern "/*" in a deployment descriptor. Patterns qualified by the "/*" pattern violate the * URLPatternSpec constraints of WebResourcePermission and WebUserDataPermission names and must be rejected by the * corresponding permission constructors. * * @param metaData - the web deployment metadata * @return HashMap<String, PatternInfo> */ static HashMap<String, PatternInfo> qualifyURLPatterns(JBossWebMetaData metaData) { ArrayList<PatternInfo> prefixList = new ArrayList<PatternInfo>(); ArrayList<PatternInfo> extensionList = new ArrayList<PatternInfo>(); ArrayList<PatternInfo> exactList = new ArrayList<PatternInfo>(); HashMap<String, PatternInfo> patternMap = new HashMap<String, PatternInfo>(); PatternInfo defaultInfo = null; List<SecurityConstraintMetaData> constraints = metaData.getSecurityConstraints(); if (constraints != null) { for (SecurityConstraintMetaData constraint : constraints) { WebResourceCollectionsMetaData resourceCollectionsMetaData = constraint.getResourceCollections(); if (resourceCollectionsMetaData != null) { for (WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData) { List<String> urlPatterns = resourceCollectionMetaData.getUrlPatterns(); for (String url : urlPatterns) { int type = getPatternType(url); PatternInfo info = patternMap.get(url); if (info == null) { info = new PatternInfo(url, type); patternMap.put(url, info); switch (type) { case PREFIX: prefixList.add(info); break; case EXTENSION: extensionList.add(info); break; case EXACT: exactList.add(info); break; case DEFAULT: defaultInfo = info; break; } } } } } } } JBossServletsMetaData servlets = metaData.getServlets(); List<ServletMappingMetaData> mappings = metaData.getServletMappings(); if(!metaData.isMetadataComplete() && servlets != null && mappings != null) { Map<String, List<String>> servletMappingMap = new HashMap<>(); for(ServletMappingMetaData mapping : mappings) { List<String> list = servletMappingMap.get(mapping.getServletName()); if(list == null) { servletMappingMap.put(mapping.getServletName(), list = new ArrayList<>()); } list.addAll(mapping.getUrlPatterns()); } for (JBossServletMetaData servlet : servlets) { ServletSecurityMetaData security = servlet.getServletSecurity(); if(security != null) { List<String> servletMappings = servletMappingMap.get(servlet.getServletName()); if(servletMappings != null) { for (String url : servletMappings) { int type = getPatternType(url); PatternInfo info = patternMap.get(url); if (info == null) { info = new PatternInfo(url, type); patternMap.put(url, info); switch (type) { case PREFIX: prefixList.add(info); break; case EXTENSION: extensionList.add(info); break; case EXACT: exactList.add(info); break; case DEFAULT: defaultInfo = info; break; } } } } } } } // Qualify all prefix patterns for (int i = 0; i < prefixList.size(); i++) { PatternInfo info = prefixList.get(i); // Qualify by every other prefix pattern matching this pattern for (int j = 0; j < prefixList.size(); j++) { if (i == j) continue; PatternInfo other = prefixList.get(j); if (info.matches(other)) info.addQualifier(other); } // Qualify by every exact pattern that is matched by this pattern for (PatternInfo other : exactList) { if (info.matches(other)) info.addQualifier(other); } } // Qualify all extension patterns for (PatternInfo info : extensionList) { // Qualify by every path prefix pattern for (PatternInfo other : prefixList) { // Any extension info.addQualifier(other); } // Qualify by every matching exact pattern for (PatternInfo other : exactList) { if (info.isExtensionFor(other)) info.addQualifier(other); } } // Qualify the default pattern if (defaultInfo == null) { defaultInfo = new PatternInfo("/", DEFAULT); patternMap.put("/", defaultInfo); } for (PatternInfo info : patternMap.values()) { if (info == defaultInfo) continue; defaultInfo.addQualifier(info); } return patternMap; } /** * A representation of all security-constraint mappings for a unique url-pattern */ static class PatternInfo { static final HashMap<String, Set<String>> ALL_TRANSPORTS = new HashMap<String, Set<String>>(); static { ALL_TRANSPORTS.put("NONE", WebResourceCollectionMetaData.ALL_HTTP_METHODS); } /** The raw url-pattern string from the web.xml */ String pattern; /** The qualified url pattern as determined by qualifyURLPatterns */ String qpattern; /** The list of qualifying patterns as determined by qualifyURLPatterns */ ArrayList<PatternInfo> qualifiers = new ArrayList<PatternInfo>(); /** One of PREFIX, EXTENSION, DEFAULT, EXACT */ int type; /** HashSet<String> Union of all http methods seen in excluded statements */ HashSet<String> excludedMethods; /** HashMap<String, HashSet<String>> role to http methods */ HashMap<String, Set<String>> roles; /** HashMap<String, HashSet<String>> transport to http methods */ HashMap<String, Set<String>> transports; /** The url pattern to http methods for patterns for */ HashSet<String> allMethods = new HashSet<String>(); /** * Does a qualifying pattern match this pattern and make this pattern obsolete? */ boolean isOverridden; /** * A Security Constraint is missing an <auth-constraint/> */ boolean isMissingAuthConstraint; Set<String> missingAuthConstraintMethods = new HashSet<>(); boolean descriptor = false; /** * @param pattern - the url-pattern value * @param type - one of EXACT, EXTENSION, PREFIX, DEFAULT */ PatternInfo(String pattern, int type) { this.pattern = pattern; this.type = type; } /** * Augment the excluded methods associated with this url * * @param httpMethods the list of excluded methods */ void addExcludedMethods(List<String> httpMethods) { Collection<String> methods = httpMethods; if (methods.isEmpty()) methods = WebResourceCollectionMetaData.ALL_HTTP_METHODS; if (excludedMethods == null) excludedMethods = new HashSet<String>(); excludedMethods.addAll(methods); allMethods.addAll(methods); } /** * Get the list of excluded http methods * * @return excluded http methods if the exist, null if there were no excluded security constraints */ public String[] getExcludedMethods() { String[] httpMethods = null; if (excludedMethods != null) { httpMethods = new String[excludedMethods.size()]; excludedMethods.toArray(httpMethods); } return httpMethods; } /** * Update the role to http methods mapping for this url. * * @param mappedRoles - the role-name values for the auth-constraint * @param httpMethods - the http-method values for the web-resource-collection */ public void addRoles(HashSet<String> mappedRoles, List<String> httpMethods) { Collection<String> methods = httpMethods; if (methods.isEmpty()) methods = WebResourceCollectionMetaData.ALL_HTTP_METHODS; allMethods.addAll(methods); if (roles == null) roles = new HashMap<String, Set<String>>(); for (String role : mappedRoles) { Set<String> roleMethods = roles.get(role); if (roleMethods == null) { roleMethods = new HashSet<String>(); roles.put(role, roleMethods); } roleMethods.addAll(methods); } } /** * Get the role to http method mappings * * @return Iterator<Map.Entry<String, Set<String>>> for the role to http method mappings. */ public Iterator<Map.Entry<String, Set<String>>> getRoleMethods() { HashMap<String, Set<String>> tmp = roles; if (tmp == null) tmp = new HashMap<String, Set<String>>(0); return tmp.entrySet().iterator(); } /** * Update the role to http methods mapping for this url. * * @param transport - the transport-guarantee value * @param httpMethods - the http-method values for the web-resource-collection */ void addTransport(String transport, List<String> httpMethods) { Collection<String> methods = httpMethods; if (methods.isEmpty()) methods = WebResourceCollectionMetaData.ALL_HTTP_METHODS; if (transports == null) transports = new HashMap<String, Set<String>>(); Set<String> transportMethods = transports.get(transport); if (transportMethods == null) { transportMethods = new HashSet<String>(); transports.put(transport, transportMethods); } transportMethods.addAll(methods); } /** * Get the transport to http method mappings * * @return Iterator<Map.Entry<String, Set<String>>> for the transport to http method mappings. */ public Iterator<Map.Entry<String, Set<String>>> getTransportMethods() { HashMap<String, Set<String>> tmp = transports; if (tmp == null) tmp = ALL_TRANSPORTS; return tmp.entrySet().iterator(); } /** * Get the list of http methods that were not associated with an excluded or role based mapping of this url. * * @return the subset of http methods that should be unchecked */ public String[] getMissingMethods() { String[] httpMethods = {}; if (allMethods.isEmpty()) { // There were no excluded or role based security-constraints httpMethods = WebResourceCollectionMetaData.ALL_HTTP_METHOD_NAMES; } else { httpMethods = WebResourceCollectionMetaData.getMissingHttpMethods(allMethods); } return httpMethods; } /** * Add the qualifying pattern. If info is a prefix pattern that matches this pattern, it overrides this pattern and will * exclude it from inclusion in the policy. * * @param info - a url pattern that should qualify this pattern */ void addQualifier(PatternInfo info) { if (qualifiers.contains(info) == false) { // See if this pattern is matched by the qualifier if (info.type == PREFIX && info.matches(this)) isOverridden = true; qualifiers.add(info); } } /** * Get the url pattern with its qualifications * * @return the qualified form of the url pattern */ public String getQualifiedPattern() { if (qpattern == null) { StringBuilder tmp = new StringBuilder(pattern); for (int n = 0; n < qualifiers.size(); n++) { tmp.append(':'); PatternInfo info = qualifiers.get(n); tmp.append(info.pattern); } qpattern = tmp.toString(); } return qpattern; } public int hashCode() { return pattern.hashCode(); } public boolean equals(Object obj) { if(!(obj instanceof PatternInfo)) { return false; } PatternInfo pi = (PatternInfo) obj; return pattern.equals(pi.pattern); } /** * See if this pattern is matches the other pattern * * @param other - another pattern * @return true if the other pattern starts with this pattern less the "/*", false otherwise */ public boolean matches(PatternInfo other) { if ("/*".equals(pattern)) { // all patterns except EXACT ones are matched (and EXACT ones are never checked) return true; } int matchLength = pattern.length() - 1; boolean matches = pattern.regionMatches(0, other.pattern, 0, matchLength); return matches; } /** * See if this is an extension pattern that matches other * * @param other - another pattern * @return true if is an extension pattern and other ends with this pattern */ public boolean isExtensionFor(PatternInfo other) { int offset = other.pattern.lastIndexOf('.'); boolean isExtensionFor = false; if (offset > 0) { isExtensionFor = other.pattern.endsWith(pattern.substring(1)); } return isExtensionFor; } public String toString() { StringBuilder tmp = new StringBuilder("PatternInfo["); tmp.append("pattern="); tmp.append(pattern); tmp.append(",type="); tmp.append(type); tmp.append(",isOverridden="); tmp.append(isOverridden); tmp.append(",qualifiers="); tmp.append(qualifiers); tmp.append("]"); return tmp.toString(); } } }
42,696
48.590012
174
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/security/jacc/JACCContextIdHandler.java
/* * 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.security.jacc; import java.security.PrivilegedAction; import jakarta.security.jacc.PolicyContext; import io.undertow.predicate.Predicates; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.PredicateHandler; import io.undertow.servlet.predicate.DispatcherTypePredicate; import org.wildfly.security.manager.WildFlySecurityManager; /** * <p> * A {@link HttpHandler} that sets the web application Jakarta Authorization contextId in the {@link PolicyContext}. Any previously registered * contextId is suspended for the duration of the request and is restored when this handler is done. * </p> * * @author <a href="mailto:[email protected]">Stefan Guilhen</a> */ public class JACCContextIdHandler implements HttpHandler { private final PrivilegedAction<String> setContextIdAction; private final HttpHandler next; public JACCContextIdHandler(String contextId, HttpHandler next) { this.setContextIdAction = new SetContextIDAction(contextId); this.next = next; } @Override public void handleRequest(final HttpServerExchange exchange) throws Exception { // set Jakarta Authorization contextID and forward the request to the next handler. String previousContextID = null; try { previousContextID = setContextID(setContextIdAction); next.handleRequest(exchange); } finally { // restore the previous Jakarta Authorization contextID. if(WildFlySecurityManager.isChecking()) { setContextID(new SetContextIDAction(previousContextID)); } else { PolicyContext.setContextID(previousContextID); } } } /** * <p> * A {@link PrivilegedAction} that sets the contextId in the {@link PolicyContext}. * </p> */ private static class SetContextIDAction implements PrivilegedAction<String> { private final String contextID; SetContextIDAction(String contextID) { this.contextID = contextID; } @Override public String run() { String currentContextID = PolicyContext.getContextID(); PolicyContext.setContextID(this.contextID); return currentContextID; } } private String setContextID(PrivilegedAction<String> action) { if(WildFlySecurityManager.isChecking()) { return WildFlySecurityManager.doUnchecked(action); }else { return action.run(); } } public static HandlerWrapper wrapper(final String contextId) { return new HandlerWrapper() { @Override public HttpHandler wrap(final HttpHandler handler) { //we only run this on REQUEST or ASYNC invocations return new PredicateHandler(Predicates.or(DispatcherTypePredicate.REQUEST, DispatcherTypePredicate.ASYNC), new JACCContextIdHandler(contextId, handler), handler); } }; } }
4,162
35.840708
178
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/security/jacc/WarJACCDeployer.java
/* * 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.security.jacc; import org.jboss.as.ee.security.AbstractSecurityDeployer; import org.jboss.as.ee.security.JaccService; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.web.common.WarMetaData; /** * Handles war deployments * * @author <a href="mailto:[email protected]">Marcus Moyses</a> */ public class WarJACCDeployer extends AbstractSecurityDeployer<WarMetaData> { /** * {@inheritDoc} */ @Override protected AttachmentKey<WarMetaData> getMetaDataType() { return WarMetaData.ATTACHMENT_KEY; } /** * {@inheritDoc} */ @Override protected JaccService<WarMetaData> createService(String contextId, WarMetaData metaData, Boolean standalone) { return new WarJACCService(contextId, metaData, standalone); } }
1,866
33.574074
114
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/security/jacc/JACCAuthorizationManager.java
/* * 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.security.jacc; import static java.security.AccessController.doPrivileged; import java.security.CodeSource; import java.security.Permission; import java.security.Policy; import java.security.Principal; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import jakarta.security.jacc.WebResourcePermission; import jakarta.security.jacc.WebRoleRefPermission; import jakarta.security.jacc.WebUserDataPermission; import jakarta.servlet.http.HttpServletRequest; import io.undertow.security.idm.Account; import io.undertow.servlet.api.AuthorizationManager; import io.undertow.servlet.api.Deployment; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.api.SingleConstraintMatch; import io.undertow.servlet.api.TransportGuaranteeType; import org.wildfly.security.manager.WildFlySecurityManager; /** * <p> * An implementation of {@link AuthorizationManager} that uses Jakarta Authorization permissions to grant or deny access to web resources. * </p> * * @author <a href="mailto:[email protected]">Stefan Guilhen</a> */ public class JACCAuthorizationManager implements AuthorizationManager { public static final AuthorizationManager INSTANCE = new JACCAuthorizationManager(); @Override public boolean isUserInRole(final String roleName, final Account account, final ServletInfo servletInfo, final HttpServletRequest request, final Deployment deployment) { return hasPermission(account, deployment, servletInfo, new WebRoleRefPermission(servletInfo.getName(), roleName)); } @Override public boolean canAccessResource(List<SingleConstraintMatch> constraints, final Account account, final ServletInfo servletInfo, final HttpServletRequest request, Deployment deployment) { return hasPermission(account, deployment, servletInfo, new WebResourcePermission(request)); } @Override public TransportGuaranteeType transportGuarantee(TransportGuaranteeType currentConnGuarantee, TransportGuaranteeType configuredRequiredGuarantee, final HttpServletRequest request) { final ProtectionDomain domain = new ProtectionDomain(null, null, null, null); final String[] httpMethod = new String[] {request.getMethod()}; final String canonicalURI = getCanonicalURI(request); switch (currentConnGuarantee) { case NONE: { // unprotected connection - create a WebUserDataPermission without any transport guarantee. WebUserDataPermission permission = new WebUserDataPermission(canonicalURI, httpMethod, null); // if permission was implied then the unprotected connection is ok. if (hasPermission(domain, permission)) { return TransportGuaranteeType.NONE; } else { permission = new WebUserDataPermission(canonicalURI, httpMethod, TransportGuaranteeType.CONFIDENTIAL.name()); // permission is only granted with CONFIDENTIAL if (hasPermission(domain, permission)) { return TransportGuaranteeType.CONFIDENTIAL; } //either way we just don't have permission, let the request proceed and be rejected later return TransportGuaranteeType.NONE; } } case INTEGRAL: case CONFIDENTIAL: { // we will try using both transport guarantees (CONFIDENTIAL and INTEGRAL) as SSL provides both. WebUserDataPermission permission = new WebUserDataPermission(canonicalURI, httpMethod, TransportGuaranteeType.CONFIDENTIAL.name()); if (hasPermission(domain, permission)) { return TransportGuaranteeType.CONFIDENTIAL; } else { // try with the INTEGRAL connection guarantee type. permission = new WebUserDataPermission(canonicalURI, httpMethod, TransportGuaranteeType.INTEGRAL.name()); if (hasPermission(domain, permission)) { return TransportGuaranteeType.INTEGRAL; } else { return TransportGuaranteeType.REJECTED; } } } default: return TransportGuaranteeType.REJECTED; } } /** * <p> * Gets the canonical request URI - that is, the request URI minus the context path. * </p> * * @param request the {@link HttpServletRequest} for which we want the canonical URI. * @return the constructed canonical URI. */ private String getCanonicalURI(HttpServletRequest request) { String canonicalURI = request.getRequestURI().substring(request.getContextPath().length()); if (canonicalURI == null || canonicalURI.equals("/")) canonicalURI = ""; return canonicalURI; } private boolean hasPermission(Account account, Deployment deployment, ServletInfo servletInfo, Permission permission) { CodeSource codeSource = servletInfo.getServletClass().getProtectionDomain().getCodeSource(); ProtectionDomain domain = new ProtectionDomain(codeSource, null, null, getGrantedRoles(account, deployment)); return hasPermission(domain, permission); } private boolean hasPermission(ProtectionDomain domain, Permission permission) { Policy policy = WildFlySecurityManager.isChecking() ? doPrivileged((PrivilegedAction<Policy>) Policy::getPolicy) : Policy.getPolicy(); return policy.implies(domain, permission); } private Principal[] getGrantedRoles(Account account, Deployment deployment) { if (account == null) { return new Principal[] {}; } Set<String> roles = new HashSet<>(account.getRoles()); Map<String, Set<String>> principalVersusRolesMap = deployment.getDeploymentInfo().getPrincipalVersusRolesMap(); roles.addAll(principalVersusRolesMap.getOrDefault(account.getPrincipal().getName(), Collections.emptySet())); Principal[] principals = new Principal[roles.size()]; int index = 0; for (String role : roles) { principals[index++] = () -> role; } return principals; } }
7,557
44.257485
190
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/sso/elytron/NonDistributableSingleSignOnManagementProvider.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, 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.sso.elytron; import org.jboss.as.clustering.controller.CapabilityServiceConfigurator; import org.jboss.msc.service.ServiceName; import org.wildfly.clustering.web.container.SecurityDomainSingleSignOnManagementConfiguration; import org.wildfly.clustering.web.container.SecurityDomainSingleSignOnManagementProvider; /** * Singleton reference to a non-distributable {@link SecurityDomainSingleSignOnManagementProvider}. * @author Paul Ferraro */ public enum NonDistributableSingleSignOnManagementProvider implements SecurityDomainSingleSignOnManagementProvider { INSTANCE; @Override public CapabilityServiceConfigurator getServiceConfigurator(ServiceName name, SecurityDomainSingleSignOnManagementConfiguration configuration) { return new DefaultSingleSignOnManagerServiceConfigurator(name, configuration); } }
1,900
44.261905
148
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/sso/elytron/DefaultSingleSignOnManagerServiceConfigurator.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, 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.sso.elytron; import java.util.concurrent.ConcurrentHashMap; import org.jboss.as.clustering.controller.SimpleCapabilityServiceConfigurator; import org.jboss.msc.service.ServiceName; import org.wildfly.clustering.web.container.SecurityDomainSingleSignOnManagementConfiguration; import org.wildfly.security.http.util.sso.DefaultSingleSignOnManager; import org.wildfly.security.http.util.sso.SingleSignOnManager; /** * Configures a srevice providing a non-distributable {@link SingleSignOnManager}. * @author Paul Ferraro */ public class DefaultSingleSignOnManagerServiceConfigurator extends SimpleCapabilityServiceConfigurator<SingleSignOnManager> { public DefaultSingleSignOnManagerServiceConfigurator(ServiceName name, SecurityDomainSingleSignOnManagementConfiguration configuration) { super(name, new DefaultSingleSignOnManager(new ConcurrentHashMap<>(), configuration.getIdentifierGenerator())); } }
1,987
45.232558
141
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/sso/elytron/SingleSignOnIdentifierFactory.java
/* * JBoss, Home of Professional Open Source. * Copyright 2018, 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.sso.elytron; import java.util.function.Supplier; import io.undertow.server.session.SecureRandomSessionIdGenerator; import io.undertow.server.session.SessionIdGenerator; /** * Adapts a {@link SessionIdGenerator} to {@link Supplier}. * @author Paul Ferraro */ public class SingleSignOnIdentifierFactory implements Supplier<String> { private final SessionIdGenerator generator; public SingleSignOnIdentifierFactory() { this(new SecureRandomSessionIdGenerator()); } public SingleSignOnIdentifierFactory(SessionIdGenerator generator) { this.generator = generator; } @Override public String get() { return this.generator.createSessionId(); } }
1,767
33.666667
72
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/logging/UndertowLogger.java
/* * 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.logging; import static org.jboss.logging.Logger.Level.ERROR; import static org.jboss.logging.Logger.Level.INFO; import static org.jboss.logging.Logger.Level.WARN; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.security.NoSuchAlgorithmException; import java.util.List; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.dmr.ModelNode; import org.jboss.jandex.AnnotationTarget; import org.jboss.jandex.ClassInfo; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; import org.jboss.msc.service.DuplicateServiceException; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartException; import org.jboss.vfs.VirtualFile; /** * @author <a href="mailto:[email protected]">James R. Perkins</a> */ @MessageLogger(projectCode = "WFLYUT", length = 4) public interface UndertowLogger extends BasicLogger { /** * A root logger with the category of the package name. */ UndertowLogger ROOT_LOGGER = Logger.getMessageLogger(UndertowLogger.class, "org.wildfly.extension.undertow"); /* UNDERTOW messages start */ @LogMessage(level = Logger.Level.ERROR) @Message(id = 1, value = "Could not initialize Jakarta Server Pages") void couldNotInitJsp(@Cause ClassNotFoundException e); // @LogMessage(level = ERROR) // @Message(id = 2, value = "Failed to purge EL cache.") // void couldNotPurgeELCache(@Cause Exception exception); @LogMessage(level = INFO) @Message(id = 3, value = "Undertow %s starting") void serverStarting(String version); @LogMessage(level = INFO) @Message(id = 4, value = "Undertow %s stopping") void serverStopping(String version); @LogMessage(level = WARN) @Message(id = 5, value = "Secure listener for protocol: '%s' not found! Using non secure port!") void secureListenerNotAvailableForPort(String protocol); /** * Creates an exception indicating the class, represented by the {@code className} parameter, cannot be accessed. * * @param name name of the listener * @param address socket address */ @LogMessage(level = INFO) @Message(id = 6, value = "Undertow %s listener %s listening on %s:%d") void listenerStarted(String type, String name, String address, int port); @LogMessage(level = INFO) @Message(id = 7, value = "Undertow %s listener %s stopped, was bound to %s:%d") void listenerStopped(String type, String name, String address, int port); @LogMessage(level = INFO) @Message(id = 8, value = "Undertow %s listener %s suspending") void listenerSuspend(String type, String name); @LogMessage(level = INFO) @Message(id = 9, value = "Could not load class designated by HandlesTypes [%s].") void cannotLoadDesignatedHandleTypes(ClassInfo classInfo, @Cause Exception e); @LogMessage(level = WARN) @Message(id = 10, value = "Could not load web socket endpoint %s.") void couldNotLoadWebSocketEndpoint(String s, @Cause Exception e); @LogMessage(level = WARN) @Message(id = 11, value = "Could not load web socket application config %s.") void couldNotLoadWebSocketConfig(String s, @Cause Exception e); @LogMessage(level = INFO) @Message(id = 12, value = "Started server %s.") void startedServer(String name); @LogMessage(level = WARN) @Message(id = 13, value = "Could not create redirect URI.") void invalidRedirectURI(@Cause Throwable cause); @LogMessage(level = INFO) @Message(id = 14, value = "Creating file handler for path '%s' with options [directory-listing: '%s', follow-symlink: '%s', case-sensitive: '%s', safe-symlink-paths: '%s']") void creatingFileHandler(String path, boolean directoryListing, boolean followSymlink, boolean caseSensitive, List<String> safePaths); // @LogMessage(level = TRACE) // @Message(id = 15, value = "registering handler %s under path '%s'") // void registeringHandler(HttpHandler value, String locationPath); @LogMessage(level = WARN) @Message(id = 16, value = "Could not resolve name in absolute ordering: %s") void invalidAbsoluteOrdering(String name); @LogMessage(level = WARN) @Message(id = 17, value = "Could not delete servlet temp file %s") void couldNotDeleteTempFile(File file); @LogMessage(level = INFO) @Message(id = 18, value = "Host %s starting") void hostStarting(String version); @LogMessage(level = INFO) @Message(id = 19, value = "Host %s stopping") void hostStopping(String version); @LogMessage(level = WARN) @Message(id = 20, value = "Clustering not supported, falling back to non-clustered session manager") void clusteringNotSupported(); @LogMessage(level = INFO) @Message(id = 21, value = "Registered web context: '%s' for server '%s'") void registerWebapp(String webappPath, String serverName); @LogMessage(level = INFO) @Message(id = 22, value = "Unregistered web context: '%s' from server '%s'") void unregisterWebapp(String webappPath, String serverName); @LogMessage(level = INFO) @Message(id = 23, value = "Skipped SCI for jar: %s.") void skippedSCI(String jar, @Cause Exception e); @LogMessage(level = Logger.Level.WARN) @Message(id = 24, value = "Failed to persist session attribute %s with value %s for session %s") void failedToPersistSessionAttribute(String attributeName, Object value, String sessionID, @Cause Exception e); //@LogMessage(level = ERROR) //@Message(id = 25, value = "Failed to register policy context handler for key %s") //void failedToRegisterPolicyContextHandler(String key, @Cause Exception e); // @Message(id = 26, value = "Unknown handler '%s' encountered") // XMLStreamException unknownHandler(String name, @Param Location location); @Message(id = 27, value = "Failed to parse XML descriptor %s at [%s,%s]") String failToParseXMLDescriptor(String xmlFile, Integer line, Integer column); @Message(id = 28, value = "Failed to parse XML descriptor %s") String failToParseXMLDescriptor(String xmlFile); @Message(id = 29, value = "@WebServlet is only allowed at class level %s") String invalidWebServletAnnotation(AnnotationTarget target); @Message(id = 30, value = "@WebInitParam requires name and value on %s") String invalidWebInitParamAnnotation(AnnotationTarget target); @Message(id = 31, value = "@WebFilter is only allowed at class level %s") String invalidWebFilterAnnotation(AnnotationTarget target); @Message(id = 32, value = "@WebListener is only allowed at class level %s") String invalidWebListenerAnnotation(AnnotationTarget target); @Message(id = 33, value = "@RunAs needs to specify a role name on %s") String invalidRunAsAnnotation(AnnotationTarget target); @Message(id = 34, value = "@DeclareRoles needs to specify role names on %s") String invalidDeclareRolesAnnotation(AnnotationTarget target); @Message(id = 35, value = "@MultipartConfig is only allowed at class level %s") String invalidMultipartConfigAnnotation(AnnotationTarget target); @Message(id = 36, value = "@ServletSecurity is only allowed at class level %s") String invalidServletSecurityAnnotation(AnnotationTarget target); @Message(id = 37, value = "%s has the wrong component type, it cannot be used as a web component") RuntimeException wrongComponentType(String clazz); @Message(id = 38, value = "TLD file %s not contained in root %s") String tldFileNotContainedInRoot(String tldPath, String rootPath); @Message(id = 39, value = "Failed to resolve module for deployment %s") DeploymentUnitProcessingException failedToResolveModule(DeploymentUnit deploymentUnit); @Message(id = 40, value = "Duplicate others in absolute ordering") String invalidMultipleOthers(); @Message(id = 41, value = "Invalid relative ordering") String invalidRelativeOrdering(); @Message(id = 42, value = "Conflict occurred processing web fragment in JAR: %s") String invalidWebFragment(String jar); @Message(id = 43, value = "Relative ordering processing error with JAR: %s") String invalidRelativeOrdering(String jar); @Message(id = 44, value = "Ordering includes both before and after others in JAR: %s") String invalidRelativeOrderingBeforeAndAfter(String jar); @Message(id = 45, value = "Duplicate name declared in JAR: %s") String invalidRelativeOrderingDuplicateName(String jar); @LogMessage(level = WARN) @Message(id = 46, value = "Unknown web fragment name declared in JAR: %s") void invalidRelativeOrderingUnknownName(String jar); @Message(id = 47, value = "Relative ordering conflict with JAR: %s") String invalidRelativeOrderingConflict(String jar); @Message(id = 48, value = "Failed to process WEB-INF/lib: %s") String failToProcessWebInfLib(VirtualFile xmlFile); @Message(id = 49, value = "Error loading SCI from module: %s") DeploymentUnitProcessingException errorLoadingSCIFromModule(String identifier, @Cause Exception e); @Message(id = 50, value = "Unable to resolve annotation index for deployment unit: %s") DeploymentUnitProcessingException unableToResolveAnnotationIndex(DeploymentUnit deploymentUnit); @Message(id = 51, value = "Deployment error processing SCI for jar: %s") DeploymentUnitProcessingException errorProcessingSCI(String jar, @Cause Exception e); @Message(id = 52, value = "Security context creation failed") RuntimeException failToCreateSecurityContext(@Cause Throwable t); @Message(id = 53, value = "No security context found") IllegalStateException noSecurityContext(); @Message(id = 54, value = "Unknown metric %s") String unknownMetric(Object metric); @Message(id = 55, value = "Null default host") IllegalArgumentException nullDefaultHost(); @Message(id = 56, value = "Null host name") IllegalStateException nullHostName(); @Message(id = 57, value = "Null parameter %s") IllegalArgumentException nullParamter(String id); @Message(id = 58, value = "Cannot activate context: %s") IllegalStateException cannotActivateContext(@Cause Throwable th, ServiceName service); @Message(id = 59, value = "Could not construct handler for class: %s. with parameters %s") RuntimeException cannotCreateHttpHandler(Class<?> handlerClass, ModelNode parameters, @Cause Throwable cause); @Message(id = 60, value = "Invalid persistent sessions directory %s") StartException invalidPersistentSessionDir(File baseDir); @Message(id = 61, value = "Failed to create persistent sessions dir %s") StartException failedToCreatePersistentSessionDir(File baseDir); @Message(id = 62, value = "Could not create log directory: %s") StartException couldNotCreateLogDirectory(Path directory, @Cause IOException e); @Message(id = 63, value = "Could not find the port number listening for protocol %s") IllegalStateException noPortListeningForProtocol(final String protocol); @Message(id = 64, value = "Failed to configure handler %s") RuntimeException failedToConfigureHandler(Class<?> handlerClass, @Cause Exception e); @Message(id = 65, value = "Handler class %s was not a handler or a wrapper") IllegalArgumentException handlerWasNotAHandlerOrWrapper(Class<?> handlerClass); @Message(id = 66, value = "Failed to configure handler %s") RuntimeException failedToConfigureHandlerClass(String handlerClass, @Cause Exception e); @Message(id = 67, value = "Servlet class not defined for servlet %s") IllegalArgumentException servletClassNotDefined(final String servletName); @LogMessage(level = ERROR) @Message(id = 68, value = "Error obtaining authorization helper") void noAuthorizationHelper(@Cause Exception e); @LogMessage(level = ERROR) @Message(id = 69, value = "Ignoring shared-session-config in jboss-all.xml in deployment %s. This entry is only valid in top level deployments.") void sharedSessionConfigNotInRootDeployment(String deployment); @Message(id = 70, value = "Could not load handler %s from %s module") RuntimeException couldNotLoadHandlerFromModule(String className, String moduleName, @Cause Exception e); @LogMessage(level = WARN) @Message(id = 71, value = "No ALPN provider found, HTTP/2 will not be enabled. To remove this message set enable-http2 to false on the listener %s in the Undertow subsystem.") void alpnNotFound(String listener); @Message(id = 72, value = "Could not find configured external path %s") DeploymentUnitProcessingException couldNotFindExternalPath(File path); @Message(id = 73, value = "mod_cluster advertise socket binding requires multicast address to be set") IllegalArgumentException advertiseSocketBindingRequiresMulticastAddress(); @LogMessage(level = ERROR) @Message(id = 74, value = "Could not find TLD %s") void tldNotFound(String location); @Message(id = 75, value = "Cannot register resource of type %s") IllegalArgumentException cannotRegisterResourceOfType(String type); @Message(id = 76, value = "Cannot remove resource of type %s") IllegalArgumentException cannotRemoveResourceOfType(String type); @LogMessage(level = ERROR) @Message(id = 78, value = "Failed to register management view for websocket %s at %s") void failedToRegisterWebsocket(Class endpoint, String path, @Cause Exception e); @LogMessage(level = ERROR) @Message(id = 77, value = "Error invoking secure response") void errorInvokingSecureResponse(@Cause Exception e); @Message(id = 79, value = "No SSL Context available from security realm '%s'. Either the realm is not configured for SSL, or the server has not been reloaded since the SSL config was added.") IllegalStateException noSslContextInSecurityRealm(String securityRealm); @LogMessage(level = WARN) @Message(id = 80, value = "Valves are no longer supported, %s is not activated.") void unsupportedValveFeature(String valve); @LogMessage(level = WARN) @Message(id = 81, value = "The deployment %s will not be distributable because this feature is disabled in web-fragment.xml of the module %s.") void distributableDisabledInFragmentXml(String deployment, String module); @Message(id = 82, value = "Could not start '%s' listener.") StartException couldNotStartListener(String name, @Cause IOException e); @Message(id = 83, value = "%s is not allowed to be null") String nullNotAllowed(String name); //@Message(id = 84, value = "There are no mechanisms available from the HttpAuthenticationFactory.") //IllegalStateException noMechanismsAvailable(); //@Message(id = 85, value = "The required mechanism '%s' is not available in mechanisms %s from the HttpAuthenticationFactory.") //IllegalStateException requiredMechanismNotAvailable(String mechanismName, Collection<String> availableMechanisms); //@Message(id = 86, value = "No authentication mechanisms have been selected.") //IllegalStateException noMechanismsSelected(); @Message(id = 87, value = "Duplicate default web module '%s' configured on server '%s', host '%s'") IllegalArgumentException duplicateDefaultWebModuleMapping(String defaultDeploymentName, String serverName, String hostName); // @LogMessage(level = WARN) // @Message(id = 88, value = "HTTP/2 will not be enabled as TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 is not enabled. You may need to install JCE to enable strong ciphers to allow HTTP/2 to function.") // void noStrongCiphers(); @Message(id = 89, value = "Predicate %s was not valid, message was: %s") String predicateNotValid(String predicate, String error); @Message(id = 90, value = "Key alias %s does not exist in the configured key store") IllegalArgumentException missingKeyStoreEntry(String alias); @Message(id = 91, value = "Key store entry %s is not a private key entry") IllegalArgumentException keyStoreEntryNotPrivate(String alias); @Message(id = 92, value = "Credential alias %s does not exist in the configured credential store") IllegalArgumentException missingCredential(String alias); @Message(id = 93, value = "Credential %s is not a clear text password") IllegalArgumentException credentialNotClearPassword(String alias); @Message(id = 94, value = "Configuration option [%s] ignored when using Elytron subsystem") @LogMessage(level = WARN) void configurationOptionIgnoredWhenUsingElytron(String option); @Message(id = 95, value = "the path ['%s'] doesn't exist on file system") String unableAddHandlerForPath(String path); //@Message(id = 96, value = "Unable to obtain identity for name %s") //IllegalStateException unableToObtainIdentity(String name, @Cause Throwable cause); @Message(id = 97, value = "If http-upgrade is enabled, remoting worker and http(s) worker must be the same. Please adjust values if need be.") String workerValueInHTTPListenerMustMatchRemoting(); @LogMessage(level = ERROR) @Message(id = 98, value = "Unexpected Authentication Error: %s") void unexceptedAuthentificationError(String errorMessage, @Cause Throwable t); @Message(id = 99, value = "Session manager not available") OperationFailedException sessionManagerNotAvailable(); @Message(id = 100, value = "Session %s not found") OperationFailedException sessionNotFound(String sessionId); @LogMessage(level = WARN) @Message(id = 101, value = "Duplicate servlet mapping %s found") void duplicateServletMapping(String mapping); @Message(id = 102, value = "The pattern %s is not a valid date pattern.") OperationFailedException invalidDateTimeFormatterPattern(String pattern); @Message(id = 103, value = "The time zone id %s is invalid.") OperationFailedException invalidTimeZoneId(String zoneId); @Message(id = 104, value = "Some classes referenced by annotation: %s in class: %s are missing.") DeploymentUnitProcessingException missingClassInAnnotation(String anCls, String resCls); @Message(id=105, value = "Host and context path are occupied, %s can't be registered. Message was: %s") DuplicateServiceException duplicateHostContextDeployments(ServiceName deploymentInfoServiceName, String errorMessage); @LogMessage(level = ERROR) @Message(id = 106, value = "Unable to generate obfuscated session route from '%s'") void unableToObfuscateSessionRoute(String route, @Cause NoSuchAlgorithmException e); @LogMessage(level = INFO) @Message(id = 107, value = "Generated obfuscated session route '%s' from '%s'") void obfuscatedSessionRoute(String obfuscatedRoute, String route); @Message(id=108, value = "The deployment is configured to use legacy security which is no longer available.") DeploymentUnitProcessingException deploymentConfiguredForLegacySecurity(); @Message(id = 109, value = "The deployment is configured to use legacy security which is no longer supported.") StartException legacySecurityUnsupported(); @Message(id = 110, value = "The use of security realms at runtime is unsupported.") OperationFailedException runtimeSecurityRealmUnsupported(); @LogMessage(level = WARN) @Message(id = 111, value = "The annotation: '%s' will have no effect on Servlet: '%s'") void badAnnotationOnServlet(String annotation, String servlet); }
20,876
45.393333
200
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/WebParsingDeploymentProcessor.java
/* * 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.deployment; import java.io.IOException; import java.io.InputStream; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.jboss.as.ee.structure.DeploymentType; import org.jboss.as.ee.structure.DeploymentTypeMarker; import org.jboss.as.ee.structure.SpecDescriptorPropertyReplacement; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.DeploymentUnitProcessor; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.as.web.common.WarMetaData; import org.jboss.metadata.parser.servlet.WebMetaDataParser; import org.jboss.metadata.parser.util.MetaDataElementParser; import org.jboss.metadata.parser.util.XMLResourceResolver; import org.jboss.metadata.parser.util.XMLSchemaValidator; import org.jboss.metadata.web.spec.WebMetaData; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.security.manager.WildFlySecurityManager; import org.xml.sax.SAXException; /** * @author Jean-Frederic Clere * @author [email protected] */ public class WebParsingDeploymentProcessor implements DeploymentUnitProcessor { private static final String WEB_XML = "WEB-INF/web.xml"; private final boolean schemaValidation; public WebParsingDeploymentProcessor() { String property = WildFlySecurityManager.getPropertyPrivileged(XMLSchemaValidator.PROPERTY_SCHEMA_VALIDATION, "false"); this.schemaValidation = Boolean.parseBoolean(property); } @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { ClassLoader old = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged(); try { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(WebParsingDeploymentProcessor.class); final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit(); if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) { return; // Skip non web deployments } final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT); final VirtualFile alternateDescriptor = deploymentRoot.getAttachment(org.jboss.as.ee.structure.Attachments.ALTERNATE_WEB_DEPLOYMENT_DESCRIPTOR); // Locate the descriptor final VirtualFile webXml; if (alternateDescriptor != null) { webXml = alternateDescriptor; } else { webXml = deploymentRoot.getRoot().getChild(WEB_XML); } final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY); assert warMetaData != null; if (webXml.exists()) { InputStream is = null; try { is = webXml.openStream(); final XMLInputFactory inputFactory = XMLInputFactory.newInstance(); MetaDataElementParser.DTDInfo dtdInfo = new MetaDataElementParser.DTDInfo(); inputFactory.setXMLResolver(dtdInfo); final XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is); WebMetaData webMetaData = WebMetaDataParser.parse(xmlReader, dtdInfo, SpecDescriptorPropertyReplacement.propertyReplacer(deploymentUnit)); if (schemaValidation && webMetaData.getSchemaLocation() != null) { XMLSchemaValidator validator = new XMLSchemaValidator(new XMLResourceResolver()); InputStream xmlInput = webXml.openStream(); ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(WebMetaDataParser.class.getClassLoader()); if (webMetaData.is23()) validator.validate("-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", xmlInput); else if (webMetaData.is24()) validator.validate("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd", xmlInput); else if (webMetaData.is25()) validator.validate("http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd", xmlInput); else if (webMetaData.is30()) validator.validate("http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd", xmlInput); else if (webMetaData.is31()) validator.validate("http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd", xmlInput); else if (webMetaData.getVersion() != null && webMetaData.getVersion().equals("4.0")) validator.validate("http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd", xmlInput); else if (webMetaData.getVersion() != null && webMetaData.getVersion().equals("5.0")) validator.validate("https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd", xmlInput); else if (webMetaData.getVersion() != null && webMetaData.getVersion().equals("6.0")) validator.validate("https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd", xmlInput); else validator.validate("-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", xmlInput); } catch (SAXException e) { throw new DeploymentUnitProcessingException("Failed to validate " + webXml, e); } finally { xmlInput.close(); Thread.currentThread().setContextClassLoader(oldCl); } } warMetaData.setWebMetaData(webMetaData); } catch (XMLStreamException e) { Integer lineNumber = null; Integer columnNumber = null; if (e.getLocation() != null) { lineNumber = e.getLocation().getLineNumber(); columnNumber = e.getLocation().getColumnNumber(); } throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(webXml.toString(), lineNumber, columnNumber), e); } catch (IOException e) { throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failToParseXMLDescriptor(webXml.toString()), e); } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } } } } finally { WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(old); } } }
8,463
53.25641
165
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/ServletResourceManager.java
/* * 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.deployment; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.jboss.vfs.VirtualFile; import io.undertow.server.handlers.resource.PathResourceManager; import io.undertow.server.handlers.resource.Resource; import io.undertow.server.handlers.resource.ResourceChangeListener; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.util.CanonicalPathUtils; /** * Resource manager that deals with overlays * * @author Stuart Douglas */ public class ServletResourceManager implements ResourceManager { public static final int TRANSFER_MIN_SIZE = 1024 * 1024; private final PathResourceManager deploymentResourceManager; private final Collection<VirtualFile> overlays; private final ResourceManager[] externalOverlays; private final boolean explodedDeployment; public ServletResourceManager(final VirtualFile resourcesRoot, final Collection<VirtualFile> overlays, boolean explodedDeployment, boolean followSymlink, boolean disableFileWatchService, List<String> externalOverlays) throws IOException { this.explodedDeployment = explodedDeployment; Path physicalFile = resourcesRoot.getPhysicalFile().toPath().toRealPath(); deploymentResourceManager = new PathResourceManager(physicalFile, TRANSFER_MIN_SIZE, true, followSymlink, !disableFileWatchService); this.overlays = overlays; if(externalOverlays == null) { this.externalOverlays = new ResourceManager[0]; } else { this.externalOverlays = new ResourceManager[externalOverlays.size()]; for (int i = 0; i < externalOverlays.size(); ++i) { String path = externalOverlays.get(i); PathResourceManager pr = new PathResourceManager(Paths.get(path).toRealPath(), TRANSFER_MIN_SIZE, true, followSymlink, !disableFileWatchService); this.externalOverlays[i] = pr; } } } @Override public Resource getResource(final String path) throws IOException { Resource res = deploymentResourceManager.getResource(path); if (res != null) { //EE.8.3.1 The content of all jar files in the WEB-INF/lib directory of the containing war //file, but not any subdirectories. if(res.getPath().startsWith("WEB-INF/lib/") && res.getPath().length() > "WEB-INF/lib/".length() && res.isDirectory()) { //if its a directory, treat it as exploded archive, dont list contents //NOTE: as is this is being run from caching resource manager, so removal of trailing '/' //is not viable return null; } return new ServletResource(this, res); } String p = path; if (p.startsWith("/")) { p = p.substring(1); } if (overlays != null) { String canonical = CanonicalPathUtils.canonicalize(p); //we don't need to do this for other resources, as the underlying RM will handle it for (VirtualFile overlay : overlays) { VirtualFile child = overlay.getChild(canonical); if (child.exists()) { try { //we make sure the child is actually a child of the parent //CanonicalPathUtils should make sure this cannot happen //but just to be safe we do it anyway child.getPathNameRelativeTo(overlay); return new ServletResource(this, new VirtualFileResource(overlay.getPhysicalFile(), child, canonical)); } catch (IllegalArgumentException ignore) { } } } } for (int i = 0; i < externalOverlays.length; ++i) { ResourceManager manager = externalOverlays[i]; res = manager.getResource(path); if(res != null) { return res; } } return null; } @Override public boolean isResourceChangeListenerSupported() { return true; } @Override public void registerResourceChangeListener(ResourceChangeListener listener) { if(explodedDeployment && deploymentResourceManager.isResourceChangeListenerSupported()) { deploymentResourceManager.registerResourceChangeListener(listener); } for(ResourceManager external : externalOverlays) { if(external.isResourceChangeListenerSupported()) { external.registerResourceChangeListener(listener); } } } @Override public void removeResourceChangeListener(ResourceChangeListener listener) { if(deploymentResourceManager.isResourceChangeListenerSupported()) { deploymentResourceManager.removeResourceChangeListener(listener); } for(ResourceManager external : externalOverlays) { if(external.isResourceChangeListenerSupported()) { external.removeResourceChangeListener(listener); } } } @Override public void close() throws IOException { deploymentResourceManager.close(); } /** * Lists all children of a particular path, taking overlays into account * * @param path The path * @return The list of children */ public List<Resource> list(String path) { try { final List<Resource> ret = new ArrayList<>(); Resource res = deploymentResourceManager.getResource(path); if (res != null) { for (Resource child : res.list()) { ret.add(new ServletResource(this, child)); } } String p = path; if (p.startsWith("/")) { p = p.substring(1); } if (overlays != null) { for (VirtualFile overlay : overlays) { VirtualFile child = overlay.getChild(p); if (child.exists()) { VirtualFileResource vfsResource = new VirtualFileResource(overlay.getPhysicalFile(), child, path); for (Resource c : vfsResource.list()) { ret.add(new ServletResource(this, c)); } } } } return ret; } catch (IOException e) { throw new RuntimeException(e); //this method really should have thrown IOException } } }
7,825
40.62766
150
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowAttachments.java
/* * 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.deployment; import java.io.File; import org.jboss.as.server.deployment.AttachmentKey; import org.jboss.as.server.deployment.AttachmentList; import org.jboss.as.web.session.SharedSessionManagerConfig; import org.wildfly.extension.undertow.ServletContainerService; import io.undertow.predicate.Predicate; import io.undertow.server.HandlerWrapper; import io.undertow.servlet.ServletExtension; import io.undertow.servlet.api.ThreadSetupHandler; import io.undertow.websockets.jsr.WebSocketDeploymentInfo; /** * Class defining {@link AttachmentKey}s for Undertow-specific attachments. * * @author Radoslav Husar * @version Oct 2013 * @since 8.0 */ public final class UndertowAttachments { public static final AttachmentKey<AttachmentList<HandlerWrapper>> UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS = AttachmentKey.createList(HandlerWrapper.class); public static final AttachmentKey<AttachmentList<HandlerWrapper>> UNDERTOW_INNER_HANDLER_CHAIN_WRAPPERS = AttachmentKey.createList(HandlerWrapper.class); public static final AttachmentKey<AttachmentList<HandlerWrapper>> UNDERTOW_OUTER_HANDLER_CHAIN_WRAPPERS = AttachmentKey.createList(HandlerWrapper.class); public static final AttachmentKey<AttachmentList<ThreadSetupHandler>> UNDERTOW_THREAD_SETUP_ACTIONS = AttachmentKey.createList(ThreadSetupHandler.class); public static final AttachmentKey<AttachmentList<ServletExtension>> UNDERTOW_SERVLET_EXTENSIONS = AttachmentKey.createList(ServletExtension.class); @Deprecated public static final AttachmentKey<SharedSessionManagerConfig> SHARED_SESSION_MANAGER_CONFIG = SharedSessionManagerConfig.ATTACHMENT_KEY; public static final AttachmentKey<WebSocketDeploymentInfo> WEB_SOCKET_DEPLOYMENT_INFO = AttachmentKey.create(WebSocketDeploymentInfo.class); public static final AttachmentKey<AttachmentList<File>> EXTERNAL_RESOURCES = AttachmentKey.createList(File.class); public static final AttachmentKey<ServletContainerService> SERVLET_CONTAINER_SERVICE = AttachmentKey.create(ServletContainerService.class); public static final AttachmentKey<AttachmentList<Predicate>> ALLOW_REQUEST_WHEN_SUSPENDED = AttachmentKey.createList(Predicate.class); public static final AttachmentKey<String> DEFAULT_SECURITY_DOMAIN = AttachmentKey.create(String.class); public static final AttachmentKey<String> RESOLVED_SECURITY_DOMAIN = AttachmentKey.create(String.class); private UndertowAttachments() { } }
3,520
45.946667
159
java
null
wildfly-main/undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java
/* * 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.deployment; import io.undertow.Handlers; import io.undertow.jsp.JspFileHandler; import io.undertow.jsp.JspServletBuilder; import io.undertow.predicate.Predicate; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.security.api.AuthenticationMode; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.builder.PredicatedHandler; import io.undertow.server.handlers.resource.CachingResourceManager; import io.undertow.server.handlers.resource.FileResourceManager; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.server.session.SecureRandomSessionIdGenerator; import io.undertow.servlet.ServletExtension; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.AuthMethodConfig; import io.undertow.servlet.api.ClassIntrospecter; import io.undertow.servlet.api.ConfidentialPortManager; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.ErrorPage; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.HttpMethodSecurityInfo; import io.undertow.servlet.api.InstanceFactory; import io.undertow.servlet.api.InstanceHandle; import io.undertow.servlet.api.ListenerInfo; import io.undertow.servlet.api.LoginConfig; import io.undertow.servlet.api.MimeMapping; import io.undertow.servlet.api.SecurityConstraint; import io.undertow.servlet.api.ServletContainerInitializerInfo; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.api.ServletSecurityInfo; import io.undertow.servlet.api.ServletSessionConfig; import io.undertow.servlet.api.SessionConfigWrapper; import io.undertow.servlet.api.SessionManagerFactory; import io.undertow.servlet.api.ThreadSetupHandler; import io.undertow.servlet.api.WebResourceCollection; import io.undertow.servlet.handlers.DefaultServlet; import io.undertow.servlet.handlers.ServletPathMatches; import io.undertow.servlet.util.ImmediateInstanceFactory; import io.undertow.websockets.extensions.PerMessageDeflateHandshake; import io.undertow.websockets.jsr.ServerWebSocketContainer; import io.undertow.websockets.jsr.UndertowContainerProvider; import io.undertow.websockets.jsr.WebSocketDeploymentInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagLibraryInfo; import org.apache.jasper.servlet.JspServlet; import org.jboss.as.ee.component.ComponentRegistry; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.server.deployment.SetupAction; import org.jboss.as.server.suspend.ServerActivity; import org.jboss.as.server.suspend.ServerActivityCallback; import org.jboss.as.server.suspend.SuspendController; import org.jboss.as.web.common.CachingWebInjectionContainer; import org.jboss.as.web.common.ExpressionFactoryWrapper; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.as.web.session.SharedSessionManagerConfig; import org.jboss.metadata.javaee.jboss.RunAsIdentityMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.CookieConfigMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.ErrorPageMetaData; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.JspConfigMetaData; import org.jboss.metadata.web.spec.JspPropertyGroupMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.LocaleEncodingMetaData; import org.jboss.metadata.web.spec.LoginConfigMetaData; import org.jboss.metadata.web.spec.MimeMappingMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.SecurityConstraintMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.SessionConfigMetaData; import org.jboss.metadata.web.spec.SessionTrackingModeType; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.WebResourceCollectionMetaData; import org.jboss.modules.Module; 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.vfs.VirtualFile; import org.wildfly.extension.requestcontroller.ControlPoint; import org.wildfly.extension.undertow.Host; import org.wildfly.extension.undertow.JSPConfig; import org.wildfly.extension.undertow.ServletContainerService; import org.wildfly.extension.undertow.CookieConfig; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.UndertowService; import org.wildfly.extension.undertow.ApplicationSecurityDomainDefinition.Registration; import org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler; 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.SecurityDomain; import org.wildfly.security.http.HttpServerAuthenticationMechanismFactory; import org.xnio.IoUtils; import jakarta.servlet.Filter; import jakarta.servlet.Servlet; import jakarta.servlet.ServletContainerInitializer; import jakarta.servlet.SessionTrackingMode; import jakarta.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.AUTHENTICATE; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.DENY; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.PERMIT; import org.jboss.as.server.ServerEnvironment; /** * Service that builds up the undertow metadata. * * @author Stuart Douglas * @author <a href="mailto:[email protected]">Richard Opalka</a> */ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> { public static final ServiceName SERVICE_NAME = ServiceName.of("UndertowDeploymentInfoService"); public static final String DEFAULT_SERVLET_NAME = "default"; public static final String UNDERTOW = "undertow"; private DeploymentInfo deploymentInfo; private Registration registration; private final AtomicReference<ServerActivity> serverActivity = new AtomicReference<>(); private final JBossWebMetaData mergedMetaData; private final String deploymentName; private final Module module; private final HashMap<String, TagLibraryInfo> tldInfo; private final ScisMetaData scisMetaData; private final VirtualFile deploymentRoot; private final String jaccContextId; private final String securityDomain; private final List<ServletContextAttribute> attributes; private final String contextPath; private final List<SetupAction> setupActions; private final Set<VirtualFile> overlays; private final List<ExpressionFactoryWrapper> expressionFactoryWrappers; private final List<PredicatedHandler> predicatedHandlers; private final List<HandlerWrapper> initialHandlerChainWrappers; private final List<HandlerWrapper> innerHandlerChainWrappers; private final List<HandlerWrapper> outerHandlerChainWrappers; private final List<ThreadSetupHandler> threadSetupActions; private final List<ServletExtension> servletExtensions; private final SharedSessionManagerConfig sharedSessionManagerConfig; private final boolean explodedDeployment; private final Consumer<DeploymentInfo> deploymentInfoConsumer; private final Supplier<UndertowService> undertowService; private final Supplier<SessionManagerFactory> sessionManagerFactory; private final Supplier<Function<CookieConfig, SessionConfigWrapper>> sessionConfigWrapperFactory; private final Supplier<ServletContainerService> container; private final Supplier<ComponentRegistry> componentRegistry; private final Supplier<Host> host; private final Supplier<ControlPoint> controlPoint; private final Supplier<SuspendController> suspendController; private final Supplier<ServerEnvironment> serverEnvironment; private final Supplier<SecurityDomain> rawSecurityDomain; private final Supplier<HttpServerAuthenticationMechanismFactory> rawMechanismFactory; private final Supplier<BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration>> applySecurityFunction; private final Map<String, Supplier<Executor>> executorsByName = new HashMap<>(); private final WebSocketDeploymentInfo webSocketDeploymentInfo; private final File tempDir; private final List<File> externalResources; private final List<Predicate> allowSuspendedRequests; private UndertowDeploymentInfoService( final Consumer<DeploymentInfo> deploymentInfoConsumer, final Supplier<UndertowService> undertowService, final Supplier<SessionManagerFactory> sessionManagerFactory, final Supplier<Function<CookieConfig, SessionConfigWrapper>> sessionConfigWrapperFactory, final Supplier<ServletContainerService> container, final Supplier<ComponentRegistry> componentRegistry, final Supplier<Host> host, final Supplier<ControlPoint> controlPoint, final Supplier<SuspendController> suspendController, final Supplier<ServerEnvironment> serverEnvironment, final Supplier<SecurityDomain> rawSecurityDomain, final Supplier<HttpServerAuthenticationMechanismFactory> rawMechanismFactory, final Supplier<BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration>> applySecurityFunction, final JBossWebMetaData mergedMetaData, final String deploymentName, final HashMap<String, TagLibraryInfo> tldInfo, final Module module, final ScisMetaData scisMetaData, final VirtualFile deploymentRoot, final String jaccContextId, final String securityDomain, final List<ServletContextAttribute> attributes, final String contextPath, final List<SetupAction> setupActions, final Set<VirtualFile> overlays, final List<ExpressionFactoryWrapper> expressionFactoryWrappers, List<PredicatedHandler> predicatedHandlers, List<HandlerWrapper> initialHandlerChainWrappers, List<HandlerWrapper> innerHandlerChainWrappers, List<HandlerWrapper> outerHandlerChainWrappers, List<ThreadSetupHandler> threadSetupActions, boolean explodedDeployment, List<ServletExtension> servletExtensions, SharedSessionManagerConfig sharedSessionManagerConfig, WebSocketDeploymentInfo webSocketDeploymentInfo, File tempDir, List<File> externalResources, List<Predicate> allowSuspendedRequests) { this.deploymentInfoConsumer = deploymentInfoConsumer; this.undertowService = undertowService; this.sessionManagerFactory = sessionManagerFactory; this.sessionConfigWrapperFactory = sessionConfigWrapperFactory; this.container = container; this.componentRegistry = componentRegistry; this.host = host; this.controlPoint = controlPoint; this.suspendController = suspendController; this.serverEnvironment = serverEnvironment; this.rawSecurityDomain = rawSecurityDomain; this.rawMechanismFactory = rawMechanismFactory; this.applySecurityFunction = applySecurityFunction; this.mergedMetaData = mergedMetaData; this.deploymentName = deploymentName; this.tldInfo = tldInfo; this.module = module; this.scisMetaData = scisMetaData; this.deploymentRoot = deploymentRoot; this.jaccContextId = jaccContextId; this.securityDomain = securityDomain; this.attributes = attributes; this.contextPath = contextPath; this.setupActions = setupActions; this.overlays = overlays; this.expressionFactoryWrappers = expressionFactoryWrappers; this.predicatedHandlers = predicatedHandlers; this.initialHandlerChainWrappers = initialHandlerChainWrappers; this.innerHandlerChainWrappers = innerHandlerChainWrappers; this.outerHandlerChainWrappers = outerHandlerChainWrappers; this.threadSetupActions = threadSetupActions; this.explodedDeployment = explodedDeployment; this.servletExtensions = servletExtensions; this.sharedSessionManagerConfig = sharedSessionManagerConfig; this.webSocketDeploymentInfo = webSocketDeploymentInfo; this.tempDir = tempDir; this.externalResources = externalResources; this.allowSuspendedRequests = allowSuspendedRequests; } @Override public synchronized void start(final StartContext startContext) throws StartException { ClassLoader oldTccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(module.getClassLoader()); DeploymentInfo deploymentInfo = createServletConfig(); deploymentInfo.setConfidentialPortManager(getConfidentialPortManager()); handleDistributable(deploymentInfo); if (!isElytronActive()) { if (securityDomain != null || mergedMetaData.isUseJBossAuthorization()) { throw UndertowLogger.ROOT_LOGGER.legacySecurityUnsupported(); } else { deploymentInfo.setSecurityDisabled(true); } } handleAdditionalAuthenticationMechanisms(deploymentInfo); SessionConfigMetaData sessionConfig = mergedMetaData.getSessionConfig(); if(sharedSessionManagerConfig != null && sharedSessionManagerConfig.getSessionConfig() != null) { sessionConfig = sharedSessionManagerConfig.getSessionConfig(); } ServletSessionConfig config = null; //default session config CookieConfig defaultSessionConfig = container.get().getSessionCookieConfig(); if (defaultSessionConfig != null) { config = new ServletSessionConfig(); if (defaultSessionConfig.getName() != null) { config.setName(defaultSessionConfig.getName()); } if (defaultSessionConfig.getDomain() != null) { config.setDomain(defaultSessionConfig.getDomain()); } if (defaultSessionConfig.getHttpOnly() != null) { config.setHttpOnly(defaultSessionConfig.getHttpOnly()); } if (defaultSessionConfig.getSecure() != null) { config.setSecure(defaultSessionConfig.getSecure()); } if (defaultSessionConfig.getMaxAge() != null) { config.setMaxAge(defaultSessionConfig.getMaxAge()); } } SecureRandomSessionIdGenerator sessionIdGenerator = new SecureRandomSessionIdGenerator(); sessionIdGenerator.setLength(container.get().getSessionIdLength()); deploymentInfo.setSessionIdGenerator(sessionIdGenerator); boolean sessionTimeoutSet = false; if (sessionConfig != null) { if (sessionConfig.getSessionTimeoutSet()) { deploymentInfo.setDefaultSessionTimeout(sessionConfig.getSessionTimeout() * 60); sessionTimeoutSet = true; } CookieConfigMetaData cookieConfig = sessionConfig.getCookieConfig(); if (config == null) { config = new ServletSessionConfig(); } if (cookieConfig != null) { if (cookieConfig.getName() != null) { config.setName(cookieConfig.getName()); } if (cookieConfig.getDomain() != null) { config.setDomain(cookieConfig.getDomain()); } config.setSecure(cookieConfig.getSecure()); config.setPath(cookieConfig.getPath()); config.setMaxAge(cookieConfig.getMaxAge()); config.setHttpOnly(cookieConfig.getHttpOnly()); } List<SessionTrackingModeType> modes = sessionConfig.getSessionTrackingModes(); if (modes != null && !modes.isEmpty()) { final Set<SessionTrackingMode> trackingModes = new HashSet<>(); for (SessionTrackingModeType mode : modes) { switch (mode) { case COOKIE: trackingModes.add(SessionTrackingMode.COOKIE); break; case SSL: trackingModes.add(SessionTrackingMode.SSL); break; case URL: trackingModes.add(SessionTrackingMode.URL); break; } } config.setSessionTrackingModes(trackingModes); } } if(!sessionTimeoutSet) { deploymentInfo.setDefaultSessionTimeout(container.get().getDefaultSessionTimeout() * 60); } if (config != null) { deploymentInfo.setServletSessionConfig(config); } for (final SetupAction action : setupActions) { deploymentInfo.addThreadSetupAction(new UndertowThreadSetupAction(action)); } if (initialHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : initialHandlerChainWrappers) { deploymentInfo.addInitialHandlerChainWrapper(handlerWrapper); } } if (innerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : innerHandlerChainWrappers) { deploymentInfo.addInnerHandlerChainWrapper(handlerWrapper); } } if (outerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : outerHandlerChainWrappers) { deploymentInfo.addOuterHandlerChainWrapper(handlerWrapper); } } if (threadSetupActions != null) { for (ThreadSetupHandler threadSetupAction : threadSetupActions) { deploymentInfo.addThreadSetupAction(threadSetupAction); } } deploymentInfo.setServerName(serverEnvironment.get().getProductConfig().getPrettyVersionString()); if (undertowService.get().isStatisticsEnabled()) { deploymentInfo.setMetricsCollector(new UndertowMetricsCollector()); } ControlPoint controlPoint = this.controlPoint != null ? this.controlPoint.get() : null; if (controlPoint != null) { deploymentInfo.addOuterHandlerChainWrapper(GlobalRequestControllerHandler.wrapper(controlPoint, allowSuspendedRequests)); } deploymentInfoConsumer.accept(this.deploymentInfo = deploymentInfo); } finally { Thread.currentThread().setContextClassLoader(oldTccl); } } @Override public synchronized void stop(final StopContext stopContext) { // Remove the server activity final ServerActivity activity = serverActivity.get(); if(activity != null) { suspendController.get().unRegisterActivity(activity); } if (System.getSecurityManager() == null) { UndertowContainerProvider.removeContainer(module.getClassLoader()); } else { AccessController.doPrivileged(new PrivilegedAction<Object>() { @Override public Object run() { UndertowContainerProvider.removeContainer(module.getClassLoader()); return null; } }); } deploymentInfoConsumer.accept(null); IoUtils.safeClose(this.deploymentInfo.getResourceManager()); this.deploymentInfo.setConfidentialPortManager(null); this.deploymentInfo = null; if (registration != null) { registration.cancel(); } } @Override public synchronized DeploymentInfo getValue() throws IllegalStateException, IllegalArgumentException { return deploymentInfo; } private void handleAdditionalAuthenticationMechanisms(final DeploymentInfo deploymentInfo) { for (Map.Entry<String, AuthenticationMechanism> am : host.get().getAdditionalAuthenticationMechanisms().entrySet()) { deploymentInfo.addFirstAuthenticationMechanism(am.getKey(), am.getValue()); } } private ConfidentialPortManager getConfidentialPortManager() { return new ConfidentialPortManager() { @Override public int getConfidentialPort(HttpServerExchange exchange) { int port = exchange.getConnection().getLocalAddress(InetSocketAddress.class).getPort(); if (port<0){ UndertowLogger.ROOT_LOGGER.debugf("Confidential port not defined for port %s", port); } return host.get().getServer().lookupSecurePort(port); } }; } private void handleDistributable(final DeploymentInfo deploymentInfo) { SessionManagerFactory managerFactory = this.sessionManagerFactory != null ? this.sessionManagerFactory.get() : null; if (managerFactory != null) { deploymentInfo.setSessionManagerFactory(managerFactory); } Function<CookieConfig, SessionConfigWrapper> sessionConfigWrapperFactory = this.sessionConfigWrapperFactory != null ? this.sessionConfigWrapperFactory.get() : null; if (sessionConfigWrapperFactory != null) { deploymentInfo.setSessionConfigWrapper(sessionConfigWrapperFactory.apply(this.container.get().getAffinityCookieConfig())); } } private DeploymentInfo createServletConfig() throws StartException { final ComponentRegistry componentRegistry = this.componentRegistry.get(); try { if (!mergedMetaData.isMetadataComplete()) { mergedMetaData.resolveAnnotations(); } mergedMetaData.resolveRunAs(); final DeploymentInfo d = new DeploymentInfo(); d.setContextPath(contextPath); if (mergedMetaData.getDescriptionGroup() != null) { d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName()); } d.setDeploymentName(deploymentName); d.setHostName(host.get().getName()); final ServletContainerService servletContainer = container.get(); try { //TODO: make the caching limits configurable List<String> externalOverlays = mergedMetaData.getOverlays(); ResourceManager resourceManager = new ServletResourceManager(deploymentRoot, overlays, explodedDeployment, mergedMetaData.isSymbolicLinkingEnabled(), servletContainer.isDisableFileWatchService(), externalOverlays); resourceManager = new CachingResourceManager(servletContainer.getFileCacheMetadataSize(), servletContainer.getFileCacheMaxFileSize(), servletContainer.getBufferCache(), resourceManager, servletContainer.getFileCacheTimeToLive() == null ? (explodedDeployment ? 2000 : -1) : servletContainer.getFileCacheTimeToLive()); if(externalResources != null && !externalResources.isEmpty()) { //TODO: we don't cache external deployments, as they are intended for development use //should be make this configurable or something? List<ResourceManager> delegates = new ArrayList<>(); for(File resource : externalResources) { delegates.add(new FileResourceManager(resource.getCanonicalFile(), 1024, true, mergedMetaData.isSymbolicLinkingEnabled(), "/")); } delegates.add(resourceManager); resourceManager = new DelegatingResourceManager(delegates); } d.setResourceManager(resourceManager); } catch (IOException e) { throw new StartException(e); } d.setTempDir(tempDir); d.setClassLoader(module.getClassLoader()); final String servletVersion = mergedMetaData.getServletVersion(); if (servletVersion != null) { d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + "")); d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + "")); } else { d.setMajorVersion(3); d.setMinorVersion(1); } d.setDefaultCookieVersion(servletContainer.getDefaultCookieVersion()); //in most cases flush just hurts performance for no good reason d.setIgnoreFlush(servletContainer.isIgnoreFlush()); //controls initialization of filters on start of application d.setEagerFilterInit(servletContainer.isEagerFilterInit()); d.setAllowNonStandardWrappers(servletContainer.isAllowNonStandardWrappers()); d.setServletStackTraces(servletContainer.getStackTraces()); d.setDisableCachingForSecuredPages(servletContainer.isDisableCachingForSecuredPages()); if(servletContainer.isDisableSessionIdReuse()) { d.setCheckOtherSessionManagers(false); } if (servletContainer.getSessionPersistenceManager() != null) { d.setSessionPersistenceManager(servletContainer.getSessionPersistenceManager()); } d.setOrphanSessionAllowed(servletContainer.isOrphanSessionAllowed()); //for 2.2 apps we do not require a leading / in path mappings boolean is22OrOlder; if (d.getMajorVersion() == 1) { is22OrOlder = true; } else if (d.getMajorVersion() == 2) { is22OrOlder = d.getMinorVersion() < 3; } else { is22OrOlder = false; } JSPConfig jspConfig = servletContainer.getJspConfig(); final Set<String> seenMappings = new HashSet<>(); //default Jakarta Server Pages servlet final ServletInfo jspServlet = jspConfig != null ? jspConfig.createJSPServletInfo() : null; if (jspServlet != null) { //this would be null if jsp support is disabled HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData); JspServletBuilder.setupDeployment(d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(new CachingWebInjectionContainer(module.getClassLoader(), componentRegistry))); if (mergedMetaData.getJspConfig() != null) { Collection<JspPropertyGroup> values = new LinkedHashSet<>(propertyGroups.values()); d.setJspConfigDescriptor(new JspConfigDescriptorImpl(tldInfo.values(), values)); } d.addServlet(jspServlet); final Set<String> jspPropertyGroupMappings = propertyGroups.keySet(); for (final String mapping : jspPropertyGroupMappings) { if(!jspServlet.getMappings().contains(mapping)) { jspServlet.addMapping(mapping); } } seenMappings.addAll(jspPropertyGroupMappings); //setup Jakarta Server Pages application context initializing listener d.addListener(new ListenerInfo(JspInitializationListener.class)); d.addServletContextAttribute(JspInitializationListener.CONTEXT_KEY, expressionFactoryWrappers); } d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry)); final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>(); if (mergedMetaData.getExecutorName() != null) { d.setExecutor(executorsByName.get(mergedMetaData.getExecutorName()).get()); } Boolean proactiveAuthentication = mergedMetaData.getProactiveAuthentication(); if(proactiveAuthentication == null) { proactiveAuthentication = container.get().isProactiveAuth(); } d.setAuthenticationMode(proactiveAuthentication ? AuthenticationMode.PRO_ACTIVE : AuthenticationMode.CONSTRAINT_DRIVEN); if (servletExtensions != null) { for (ServletExtension extension : servletExtensions) { d.addServletExtension(extension); } } if (mergedMetaData.getServletMappings() != null) { for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) { List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName()); if (list == null) { servletMappings.put(mapping.getServletName(), list = new ArrayList<>()); } list.add(mapping); } } if (jspServlet != null) { jspServlet.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(null)); // we need to clear the file attribute if it is set (WFLY-4106) List<ServletMappingMetaData> list = servletMappings.get(jspServlet.getName()); if(list != null && ! list.isEmpty()) { for (final ServletMappingMetaData mapping : list) { for(String urlPattern : mapping.getUrlPatterns()) { jspServlet.addMapping(urlPattern); } seenMappings.addAll(mapping.getUrlPatterns()); } } } for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) { final ServletInfo s; if (servlet.getJspFile() != null) { s = new ServletInfo(servlet.getName(), JspServlet.class); s.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(servlet.getJspFile())); } else { if (servlet.getServletClass() == null) { if(DEFAULT_SERVLET_NAME.equals(servlet.getName())) { s = new ServletInfo(servlet.getName(), DefaultServlet.class); } else { throw UndertowLogger.ROOT_LOGGER.servletClassNotDefined(servlet.getServletName()); } } else { Class<? extends Servlet> servletClass = (Class<? extends Servlet>) module.getClassLoader().loadClass(servlet.getServletClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(servletClass, true); if (creator != null) { InstanceFactory<Servlet> factory = createInstanceFactory(creator); s = new ServletInfo(servlet.getName(), servletClass, factory); } else { s = new ServletInfo(servlet.getName(), servletClass); } } } s.setAsyncSupported(servlet.isAsyncSupported()) .setJspFile(servlet.getJspFile()) .setEnabled(servlet.isEnabled()); if (servlet.getRunAs() != null) { s.setRunAs(servlet.getRunAs().getRoleName()); } if (servlet.getLoadOnStartupSet()) {//todo why not cleanup api and just use int everywhere s.setLoadOnStartup(servlet.getLoadOnStartupInt()); } if (servlet.getExecutorName() != null) { s.setExecutor(executorsByName.get(servlet.getExecutorName()).get()); } handleServletMappings(is22OrOlder, seenMappings, servletMappings, s); if (servlet.getInitParam() != null) { for (ParamValueMetaData initParam : servlet.getInitParam()) { if (!s.getInitParams().containsKey(initParam.getParamName())) { s.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } if (servlet.getServletSecurity() != null) { ServletSecurityInfo securityInfo = new ServletSecurityInfo(); s.setServletSecurityInfo(securityInfo); securityInfo.setEmptyRoleSemantic(servlet.getServletSecurity().getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee())) .addRolesAllowed(servlet.getServletSecurity().getRolesAllowed()); if (servlet.getServletSecurity().getHttpMethodConstraints() != null) { for (HttpMethodConstraintMetaData method : servlet.getServletSecurity().getHttpMethodConstraints()) { securityInfo.addHttpMethodSecurityInfo( new HttpMethodSecurityInfo() .setEmptyRoleSemantic(method.getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(method.getTransportGuarantee())) .addRolesAllowed(method.getRolesAllowed()) .setMethod(method.getMethod())); } } } if (servlet.getSecurityRoleRefs() != null) { for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) { s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink()); } } if (servlet.getMultipartConfig() != null) { MultipartConfigMetaData mp = servlet.getMultipartConfig(); s.setMultipartConfig(Servlets.multipartConfig(mp.getLocation(), mp.getMaxFileSize(), mp.getMaxRequestSize(), mp.getFileSizeThreshold())); } d.addServlet(s); } if(jspServlet != null) { if(!seenMappings.contains("*.jsp")) { jspServlet.addMapping("*.jsp"); } if(!seenMappings.contains("*.jspx")) { jspServlet.addMapping("*.jspx"); } } //we explicitly add the default servlet, to allow it to be mapped if (!mergedMetaData.getServlets().containsKey(ServletPathMatches.DEFAULT_SERVLET_NAME)) { ServletInfo defaultServlet = Servlets.servlet(DEFAULT_SERVLET_NAME, DefaultServlet.class); handleServletMappings(is22OrOlder, seenMappings, servletMappings, defaultServlet); d.addServlet(defaultServlet); } if(servletContainer.getDirectoryListingEnabled() != null) { ServletInfo defaultServlet = d.getServlets().get(DEFAULT_SERVLET_NAME); defaultServlet.addInitParam(DefaultServlet.DIRECTORY_LISTING, servletContainer.getDirectoryListingEnabled().toString()); } if (mergedMetaData.getFilters() != null) { for (final FilterMetaData filter : mergedMetaData.getFilters()) { Class<? extends Filter> filterClass = (Class<? extends Filter>) module.getClassLoader().loadClass(filter.getFilterClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(filterClass); FilterInfo f; if (creator != null) { InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator); f = new FilterInfo(filter.getName(), filterClass, instanceFactory); } else { f = new FilterInfo(filter.getName(), filterClass); } f.setAsyncSupported(filter.isAsyncSupported()); d.addFilter(f); if (filter.getInitParam() != null) { for (ParamValueMetaData initParam : filter.getInitParam()) { f.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } } if (mergedMetaData.getFilterMappings() != null) { for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) { if (mapping.getUrlPatterns() != null) { for (String url : mapping.getUrlPatterns()) { if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) { url = "/" + url; } if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterUrlMapping(mapping.getFilterName(), url, jakarta.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterUrlMapping(mapping.getFilterName(), url, jakarta.servlet.DispatcherType.REQUEST); } } } if (mapping.getServletNames() != null) { for (String servletName : mapping.getServletNames()) { if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, jakarta.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, jakarta.servlet.DispatcherType.REQUEST); } } } } } if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) { for (final ServletContainerInitializer sci : scisMetaData.getScis()) { final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory = new ImmediateInstanceFactory<>(sci); d.addServletContainerInitalizer(new ServletContainerInitializerInfo(sci.getClass(), instanceFactory, scisMetaData.getHandlesTypes().get(sci))); } } if (mergedMetaData.getListeners() != null) { Set<String> tldListeners = new HashSet<>(); for(Map.Entry<String, TagLibraryInfo> e : tldInfo.entrySet()) { tldListeners.addAll(Arrays.asList(e.getValue().getListeners())); } for (ListenerMetaData listener : mergedMetaData.getListeners()) { addListener(module.getClassLoader(), componentRegistry, d, listener, tldListeners.contains(listener.getListenerClass())); } } if (mergedMetaData.getContextParams() != null) { for (ParamValueMetaData param : mergedMetaData.getContextParams()) { d.addInitParameter(param.getParamName(), param.getParamValue()); } } if (mergedMetaData.getWelcomeFileList() != null && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) { List<String> welcomeFiles = mergedMetaData.getWelcomeFileList().getWelcomeFiles(); for (String file : welcomeFiles) { if (file.startsWith("/")) { d.addWelcomePages(file.substring(1)); } else { d.addWelcomePages(file); } } } else { d.addWelcomePages("index.html", "index.htm", "index.jsp"); } d.addWelcomePages(servletContainer.getWelcomeFiles()); if (mergedMetaData.getErrorPages() != null) { for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) { final ErrorPage errorPage; if (page.getExceptionType() != null && !page.getExceptionType().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), (Class<? extends Throwable>) module.getClassLoader().loadClass(page.getExceptionType())); } else if (page.getErrorCode() != null && !page.getErrorCode().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode())); } else { errorPage = new ErrorPage(page.getLocation()); } d.addErrorPages(errorPage); } } for(Map.Entry<String, String> entry : servletContainer.getMimeMappings().entrySet()) { d.addMimeMapping(new MimeMapping(entry.getKey(), entry.getValue())); } if (mergedMetaData.getMimeMappings() != null) { for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) { d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType())); } } d.setDenyUncoveredHttpMethods(mergedMetaData.getDenyUncoveredHttpMethods() != null); Set<String> securityRoleNames = mergedMetaData.getSecurityRoleNames(); if (mergedMetaData.getSecurityConstraints() != null) { for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) { SecurityConstraint securityConstraint = new SecurityConstraint() .setTransportGuaranteeType(transportGuaranteeType(constraint.getTransportGuarantee())); List<String> roleNames = constraint.getRoleNames(); if (constraint.getAuthConstraint() == null) { // no auth constraint means we permit the empty roles securityConstraint.setEmptyRoleSemantic(PERMIT); } else if (roleNames.size() == 1 && roleNames.contains("*") && securityRoleNames.contains("*")) { // AS7-6932 - Trying to do a * to * mapping which JBossWeb passed through, for Undertow enable // authentication only mode. // TODO - AS7-6933 - Revisit workaround added to allow switching between JBoss Web and Undertow. securityConstraint.setEmptyRoleSemantic(AUTHENTICATE); } else { securityConstraint.addRolesAllowed(roleNames); } if (constraint.getResourceCollections() != null) { for (final WebResourceCollectionMetaData resourceCollection : constraint.getResourceCollections()) { securityConstraint.addWebResourceCollection(new WebResourceCollection() .addHttpMethods(resourceCollection.getHttpMethods()) .addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions()) .addUrlPatterns(resourceCollection.getUrlPatterns())); } } d.addSecurityConstraint(securityConstraint); } } final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig(); if (loginConfig != null) { List<AuthMethodConfig> authMethod = authMethod(loginConfig.getAuthMethod()); if (loginConfig.getFormLoginConfig() != null) { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName(), loginConfig.getFormLoginConfig().getLoginPage(), loginConfig.getFormLoginConfig().getErrorPage())); } else { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName())); } for (AuthMethodConfig method : authMethod) { d.getLoginConfig().addLastAuthMethod(method); } } d.addSecurityRoles(mergedMetaData.getSecurityRoleNames()); Map<String, Set<String>> principalVersusRolesMap = mergedMetaData.getPrincipalVersusRolesMap(); if (isElytronActive()) { Map<String, RunAsIdentityMetaData> runAsIdentityMap = mergedMetaData.getRunAsIdentity(); applyElytronSecurity(d, runAsIdentityMap::get); } else { if (securityDomain != null) { throw UndertowLogger.ROOT_LOGGER.legacySecurityUnsupported(); } } if (principalVersusRolesMap != null) { for (Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) { d.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue()); } } // Setup an deployer configured ServletContext attributes if(attributes != null) { for (ServletContextAttribute attribute : attributes) { d.addServletContextAttribute(attribute.getName(), attribute.getValue()); } } //now setup websockets if they are enabled if(servletContainer.isWebsocketsEnabled() && webSocketDeploymentInfo != null) { webSocketDeploymentInfo.setBuffers(servletContainer.getWebsocketsBufferPool()); webSocketDeploymentInfo.setWorker(servletContainer.getWebsocketsWorker()); webSocketDeploymentInfo.setDispatchToWorkerThread(servletContainer.isDispatchWebsocketInvocationToWorker()); if(servletContainer.isPerMessageDeflate()) { PerMessageDeflateHandshake perMessageDeflate = new PerMessageDeflateHandshake(false, servletContainer.getDeflaterLevel()); webSocketDeploymentInfo.addExtension(perMessageDeflate); } webSocketDeploymentInfo.addListener(wsc -> { serverActivity.set(new ServerActivity() { @Override public void preSuspend(ServerActivityCallback listener) { listener.done(); } @Override public void suspended(final ServerActivityCallback listener) { if(wsc.getConfiguredServerEndpoints().isEmpty()) { //TODO: remove this once undertow bug fix is upstream listener.done(); return; } wsc.pause(new ServerWebSocketContainer.PauseListener() { @Override public void paused() { listener.done(); } @Override public void resumed() { } }); } @Override public void resume() { wsc.resume(); } }); suspendController.get().registerActivity(serverActivity.get()); }); d.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo); } if (mergedMetaData.getLocalEncodings() != null && mergedMetaData.getLocalEncodings().getMappings() != null) { for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) { d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding()); } } if (predicatedHandlers != null && !predicatedHandlers.isEmpty()) { d.addOuterHandlerChainWrapper(new RewriteCorrectingHandlerWrappers.PostWrapper()); d.addOuterHandlerChainWrapper(new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { return Handlers.predicates(predicatedHandlers, handler); } }); d.addOuterHandlerChainWrapper(new RewriteCorrectingHandlerWrappers.PreWrapper()); } if (mergedMetaData.getDefaultEncoding() != null) { d.setDefaultEncoding(mergedMetaData.getDefaultEncoding()); } else if (servletContainer.getDefaultEncoding() != null) { d.setDefaultEncoding(servletContainer.getDefaultEncoding()); } d.setCrawlerSessionManagerConfig(servletContainer.getCrawlerSessionManagerConfig()); d.setPreservePathOnForward(servletContainer.isPreservePathOnForward()); return d; } catch (ClassNotFoundException e) { throw new StartException(e); } } private void handleServletMappings(boolean is22OrOlder, Set<String> seenMappings, Map<String, List<ServletMappingMetaData>> servletMappings, ServletInfo s) { List<ServletMappingMetaData> mappings = servletMappings.get(s.getName()); if (mappings != null) { for (ServletMappingMetaData mapping : mappings) { for (String pattern : mapping.getUrlPatterns()) { if (is22OrOlder && !pattern.startsWith("*") && !pattern.startsWith("/")) { pattern = "/" + pattern; } if (!seenMappings.contains(pattern)) { s.addMapping(pattern); seenMappings.add(pattern); } else { UndertowLogger.ROOT_LOGGER.duplicateServletMapping(pattern); } } } } } /** * Convert the authentication method name from the format specified in the web.xml to the format used by * {@link jakarta.servlet.http.HttpServletRequest}. * <p/> * If the auth method is not recognised then it is returned as-is. * * @return The converted auth method. * @throws NullPointerException if no configuredMethod is supplied. */ private static List<AuthMethodConfig> authMethod(String configuredMethod) { if (configuredMethod == null) { return Collections.singletonList(new AuthMethodConfig(HttpServletRequest.BASIC_AUTH)); } return AuthMethodParser.parse(configuredMethod, Collections.singletonMap("CLIENT-CERT", HttpServletRequest.CLIENT_CERT_AUTH)); } private static io.undertow.servlet.api.TransportGuaranteeType transportGuaranteeType(final TransportGuaranteeType type) { if (type == null) { return io.undertow.servlet.api.TransportGuaranteeType.NONE; } switch (type) { case CONFIDENTIAL: return io.undertow.servlet.api.TransportGuaranteeType.CONFIDENTIAL; case INTEGRAL: return io.undertow.servlet.api.TransportGuaranteeType.INTEGRAL; case NONE: return io.undertow.servlet.api.TransportGuaranteeType.NONE; } throw new RuntimeException("UNREACHABLE"); } private static HashMap<String, JspPropertyGroup> createJspConfig(JBossWebMetaData metaData) { final HashMap<String, JspPropertyGroup> result = new HashMap<>(); // Jakarta Server Pages Config JspConfigMetaData config = metaData.getJspConfig(); if (config != null) { // Jakarta Server Pages Property groups List<JspPropertyGroupMetaData> groups = config.getPropertyGroups(); if (groups != null) { for (JspPropertyGroupMetaData group : groups) { org.apache.jasper.deploy.JspPropertyGroup jspPropertyGroup = new org.apache.jasper.deploy.JspPropertyGroup(); for (String pattern : group.getUrlPatterns()) { jspPropertyGroup.addUrlPattern(pattern); } jspPropertyGroup.setElIgnored(group.getElIgnored()); jspPropertyGroup.setPageEncoding(group.getPageEncoding()); jspPropertyGroup.setScriptingInvalid(group.getScriptingInvalid()); jspPropertyGroup.setIsXml(group.getIsXml()); if (group.getIncludePreludes() != null) { for (String includePrelude : group.getIncludePreludes()) { jspPropertyGroup.addIncludePrelude(includePrelude); } } if (group.getIncludeCodas() != null) { for (String includeCoda : group.getIncludeCodas()) { jspPropertyGroup.addIncludeCoda(includeCoda); } } jspPropertyGroup.setDeferredSyntaxAllowedAsLiteral(group.getDeferredSyntaxAllowedAsLiteral()); jspPropertyGroup.setTrimDirectiveWhitespaces(group.getTrimDirectiveWhitespaces()); jspPropertyGroup.setDefaultContentType(group.getDefaultContentType()); jspPropertyGroup.setBuffer(group.getBuffer()); jspPropertyGroup.setErrorOnUndeclaredNamespace(group.getErrorOnUndeclaredNamespace()); for (String pattern : jspPropertyGroup.getUrlPatterns()) { // Split off the groups to individual mappings result.put(pattern, jspPropertyGroup); } } } } //it looks like jasper needs these in order of least specified to most specific final LinkedHashMap<String, JspPropertyGroup> ret = new LinkedHashMap<>(); final ArrayList<String> paths = new ArrayList<>(result.keySet()); Collections.sort(paths, new Comparator<String>() { @Override public int compare(final String o1, final String o2) { return o1.length() - o2.length(); } }); for (String path : paths) { ret.put(path, result.get(path)); } return ret; } private static void addListener(final ClassLoader classLoader, final ComponentRegistry components, final DeploymentInfo d, final ListenerMetaData listener, boolean programatic) throws ClassNotFoundException { ListenerInfo l; final Class<? extends EventListener> listenerClass = (Class<? extends EventListener>) classLoader.loadClass(listener.getListenerClass()); ManagedReferenceFactory creator = components.createInstanceFactory(listenerClass); if (creator != null) { InstanceFactory<EventListener> factory = createInstanceFactory(creator); l = new ListenerInfo(listenerClass, factory, programatic); } else { l = new ListenerInfo(listenerClass, programatic); } d.addListener(l); } private static <T> InstanceFactory<T> createInstanceFactory(final ManagedReferenceFactory creator) { return new InstanceFactory<T>() { @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference instance = creator.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) instance.getInstance(); } @Override public void release() { instance.release(); } }; } }; } /* * Elytron Security Methods */ private boolean isElytronActive() { return (applySecurityFunction != null && applySecurityFunction.get() != null) || (rawSecurityDomain != null && rawSecurityDomain.get() != null); } private void applyElytronSecurity(final DeploymentInfo deploymentInfo, Function<String, RunAsIdentityMetaData> runAsMapping) { BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration> securityFunction = applySecurityFunction != null ? applySecurityFunction.get() : null; if (securityFunction != null) { registration = securityFunction.apply(deploymentInfo, runAsMapping); } else { HttpServerAuthenticationMechanismFactory mechanismFactory = rawMechanismFactory == null ? null : rawMechanismFactory.get(); SecurityDomain securityDomain = rawSecurityDomain.get(); org.wildfly.elytron.web.undertow.server.servlet.AuthenticationManager.Builder builder = org.wildfly.elytron.web.undertow.server.servlet.AuthenticationManager.builder(); if (mechanismFactory != null) { HttpAuthenticationFactory httpAuthenticationFactory = HttpAuthenticationFactory.builder() .setFactory(mechanismFactory) .setSecurityDomain(securityDomain) .setMechanismConfigurationSelector(MechanismConfigurationSelector.constantSelector(MechanismConfiguration.EMPTY)) .build(); builder.setHttpAuthenticationFactory(httpAuthenticationFactory); builder.setOverrideDeploymentConfig(true).setRunAsMapper(runAsMapping); } else { builder = builder.setSecurityDomain(securityDomain); builder.setOverrideDeploymentConfig(true) .setRunAsMapper(runAsMapping) .setIntegratedJaspi(false) .setEnableJaspi(true); } org.wildfly.elytron.web.undertow.server.servlet.AuthenticationManager authenticationManager = builder.build(); authenticationManager.configure(deploymentInfo); } deploymentInfo.addOuterHandlerChainWrapper(JACCContextIdHandler.wrapper(jaccContextId)); if(mergedMetaData.isUseJBossAuthorization()) { UndertowLogger.ROOT_LOGGER.configurationOptionIgnoredWhenUsingElytron("use-jboss-authorization"); } } public void addInjectedExecutor(final String name, final Supplier<Executor> injected) { executorsByName.put(name, injected); } private static class ComponentClassIntrospector implements ClassIntrospecter { private final ComponentRegistry componentRegistry; public ComponentClassIntrospector(final ComponentRegistry componentRegistry) { this.componentRegistry = componentRegistry; } @Override public <T> InstanceFactory<T> createInstanceFactory(final Class<T> clazz) throws NoSuchMethodException { final ManagedReferenceFactory component = componentRegistry.createInstanceFactory(clazz); return new ManagedReferenceInstanceFactory<>(component); } } private static class ManagedReferenceInstanceFactory<T> implements InstanceFactory<T> { private final ManagedReferenceFactory component; public ManagedReferenceInstanceFactory(final ManagedReferenceFactory component) { this.component = component; } @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference reference = component.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) reference.getInstance(); } @Override public void release() { reference.release(); } }; } } public static Builder builder() { return new Builder(); } public static class Builder { private JBossWebMetaData mergedMetaData; private String deploymentName; private HashMap<String, TagLibraryInfo> tldInfo; private Module module; private ScisMetaData scisMetaData; private VirtualFile deploymentRoot; private String jaccContextId; private List<ServletContextAttribute> attributes; private String contextPath; private String securityDomain; private List<SetupAction> setupActions; private Set<VirtualFile> overlays; private List<ExpressionFactoryWrapper> expressionFactoryWrappers; private List<PredicatedHandler> predicatedHandlers; private List<HandlerWrapper> initialHandlerChainWrappers; private List<HandlerWrapper> innerHandlerChainWrappers; private List<HandlerWrapper> outerHandlerChainWrappers; private List<ThreadSetupHandler> threadSetupActions; private List<ServletExtension> servletExtensions; private SharedSessionManagerConfig sharedSessionManagerConfig; private boolean explodedDeployment; private WebSocketDeploymentInfo webSocketDeploymentInfo; private File tempDir; private List<File> externalResources; List<Predicate> allowSuspendedRequests; Builder setMergedMetaData(final JBossWebMetaData mergedMetaData) { this.mergedMetaData = mergedMetaData; return this; } public Builder setDeploymentName(final String deploymentName) { this.deploymentName = deploymentName; return this; } public Builder setTldInfo(HashMap<String, TagLibraryInfo> tldInfo) { this.tldInfo = tldInfo; return this; } public Builder setModule(final Module module) { this.module = module; return this; } public Builder setScisMetaData(final ScisMetaData scisMetaData) { this.scisMetaData = scisMetaData; return this; } public Builder setDeploymentRoot(final VirtualFile deploymentRoot) { this.deploymentRoot = deploymentRoot; return this; } public Builder setJaccContextId(final String jaccContextId) { this.jaccContextId = jaccContextId; return this; } public Builder setAttributes(final List<ServletContextAttribute> attributes) { this.attributes = attributes; return this; } public Builder setContextPath(final String contextPath) { this.contextPath = contextPath; return this; } public Builder setSetupActions(final List<SetupAction> setupActions) { this.setupActions = setupActions; return this; } public Builder setSecurityDomain(final String securityDomain) { this.securityDomain = securityDomain; return this; } public Builder setOverlays(final Set<VirtualFile> overlays) { this.overlays = overlays; return this; } public Builder setExpressionFactoryWrappers(final List<ExpressionFactoryWrapper> expressionFactoryWrappers) { this.expressionFactoryWrappers = expressionFactoryWrappers; return this; } public Builder setPredicatedHandlers(List<PredicatedHandler> predicatedHandlers) { this.predicatedHandlers = predicatedHandlers; return this; } public Builder setInitialHandlerChainWrappers(List<HandlerWrapper> initialHandlerChainWrappers) { this.initialHandlerChainWrappers = initialHandlerChainWrappers; return this; } public Builder setInnerHandlerChainWrappers(List<HandlerWrapper> innerHandlerChainWrappers) { this.innerHandlerChainWrappers = innerHandlerChainWrappers; return this; } public Builder setOuterHandlerChainWrappers(List<HandlerWrapper> outerHandlerChainWrappers) { this.outerHandlerChainWrappers = outerHandlerChainWrappers; return this; } public Builder setThreadSetupActions(List<ThreadSetupHandler> threadSetupActions) { this.threadSetupActions = threadSetupActions; return this; } public Builder setExplodedDeployment(boolean explodedDeployment) { this.explodedDeployment = explodedDeployment; return this; } public List<ServletExtension> getServletExtensions() { return servletExtensions; } public Builder setServletExtensions(List<ServletExtension> servletExtensions) { this.servletExtensions = servletExtensions; return this; } public Builder setSharedSessionManagerConfig(SharedSessionManagerConfig sharedSessionManagerConfig) { this.sharedSessionManagerConfig = sharedSessionManagerConfig; return this; } public Builder setWebSocketDeploymentInfo(WebSocketDeploymentInfo webSocketDeploymentInfo) { this.webSocketDeploymentInfo = webSocketDeploymentInfo; return this; } public File getTempDir() { return tempDir; } public Builder setTempDir(File tempDir) { this.tempDir = tempDir; return this; } public Builder setAllowSuspendedRequests(List<Predicate> allowSuspendedRequests) { this.allowSuspendedRequests = allowSuspendedRequests; return this; } public Builder setExternalResources(List<File> externalResources) { this.externalResources = externalResources; return this; } public UndertowDeploymentInfoService createUndertowDeploymentInfoService( final Consumer<DeploymentInfo> deploymentInfoConsumer, final Supplier<UndertowService> undertowService, final Supplier<SessionManagerFactory> sessionManagerFactory, final Supplier<Function<CookieConfig, SessionConfigWrapper>> sessionConfigWrapperFactory, final Supplier<ServletContainerService> container, final Supplier<ComponentRegistry> componentRegistry, final Supplier<Host> host, final Supplier<ControlPoint> controlPoint, final Supplier<SuspendController> suspendController, final Supplier<ServerEnvironment> serverEnvironment, final Supplier<SecurityDomain> rawSecurityDomain, final Supplier<HttpServerAuthenticationMechanismFactory> rawMechanismFactory, final Supplier<BiFunction<DeploymentInfo, Function<String, RunAsIdentityMetaData>, Registration>> applySecurityFunction ) { return new UndertowDeploymentInfoService(deploymentInfoConsumer, undertowService, sessionManagerFactory, sessionConfigWrapperFactory, container, componentRegistry, host, controlPoint, suspendController, serverEnvironment, rawSecurityDomain, rawMechanismFactory, applySecurityFunction, mergedMetaData, deploymentName, tldInfo, module, scisMetaData, deploymentRoot, jaccContextId, securityDomain, attributes, contextPath, setupActions, overlays, expressionFactoryWrappers, predicatedHandlers, initialHandlerChainWrappers, innerHandlerChainWrappers, outerHandlerChainWrappers, threadSetupActions, explodedDeployment, servletExtensions, sharedSessionManagerConfig, webSocketDeploymentInfo, tempDir, externalResources, allowSuspendedRequests); } } private static class UndertowThreadSetupAction implements ThreadSetupHandler { private final SetupAction action; private UndertowThreadSetupAction(SetupAction action) { this.action = action; } @Override public <T, C> Action<T, C> create(Action<T, C> action) { return (exchange, context) -> { UndertowThreadSetupAction.this.action.setup(Collections.emptyMap()); try { return action.call(exchange, context); } finally { UndertowThreadSetupAction.this.action.teardown(Collections.emptyMap()); } }; } } }
72,064
49.114743
975
java