HandshakeWebSocketService.java 8.8 KB
Newer Older
1
/*
2
 * Copyright 2002-2018 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15
 *
 * 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.
 */
16

17 18
package org.springframework.web.reactive.socket.server.support;

19
import java.security.Principal;
20 21
import java.util.Collections;
import java.util.List;
22 23 24
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
25 26 27 28 29

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Mono;

30
import org.springframework.context.Lifecycle;
R
Rossen Stoyanchev 已提交
31
import org.springframework.http.HttpHeaders;
32 33
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
34
import org.springframework.lang.Nullable;
35 36 37
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
38
import org.springframework.util.StringUtils;
39
import org.springframework.web.reactive.socket.HandshakeInfo;
40 41 42 43 44
import org.springframework.web.reactive.socket.WebSocketHandler;
import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy;
import org.springframework.web.reactive.socket.server.WebSocketService;
import org.springframework.web.server.MethodNotAllowedException;
import org.springframework.web.server.ServerWebExchange;
R
Rossen Stoyanchev 已提交
45
import org.springframework.web.server.ServerWebInputException;
46 47

/**
48 49 50 51
 * {@code WebSocketService} implementation that handles a WebSocket HTTP
 * handshake request by delegating to a {@link RequestUpgradeStrategy} which
 * is either auto-detected (no-arg constructor) from the classpath but can
 * also be explicitly configured.
52 53 54 55
 *
 * @author Rossen Stoyanchev
 * @since 5.0
 */
56
public class HandshakeWebSocketService implements WebSocketService, Lifecycle {
57 58 59

	private static final String SEC_WEBSOCKET_KEY = "Sec-WebSocket-Key";

60 61
	private static final String SEC_WEBSOCKET_PROTOCOL = "Sec-WebSocket-Protocol";

62 63
	private static final Mono<Map<String, Object>> EMPTY_ATTRIBUTES = Mono.just(Collections.emptyMap());

64

65 66 67 68 69 70 71 72 73 74
	private static final boolean tomcatPresent = ClassUtils.isPresent(
			"org.apache.tomcat.websocket.server.WsHttpUpgradeHandler",
			HandshakeWebSocketService.class.getClassLoader());

	private static final boolean jettyPresent = ClassUtils.isPresent(
			"org.eclipse.jetty.websocket.server.WebSocketServerFactory",
			HandshakeWebSocketService.class.getClassLoader());

	private static final boolean undertowPresent = ClassUtils.isPresent(
			"io.undertow.websockets.WebSocketProtocolHandshakeHandler",
75 76
			HandshakeWebSocketService.class.getClassLoader());

77
	private static final boolean reactorNettyPresent = ClassUtils.isPresent(
V
Violeta Georgieva 已提交
78
			"reactor.netty.http.server.HttpServerResponse",
79 80
			HandshakeWebSocketService.class.getClassLoader());

81 82 83 84 85 86

	protected static final Log logger = LogFactory.getLog(HandshakeWebSocketService.class);


	private final RequestUpgradeStrategy upgradeStrategy;

87 88 89
	@Nullable
	private Predicate<String> sessionAttributePredicate;

90 91
	private volatile boolean running = false;

92 93 94 95 96 97 98 99 100 101 102 103 104 105

	/**
	 * Default constructor automatic, classpath detection based discovery of the
	 * {@link RequestUpgradeStrategy} to use.
	 */
	public HandshakeWebSocketService() {
		this(initUpgradeStrategy());
	}

	/**
	 * Alternative constructor with the {@link RequestUpgradeStrategy} to use.
	 * @param upgradeStrategy the strategy to use
	 */
	public HandshakeWebSocketService(RequestUpgradeStrategy upgradeStrategy) {
106
		Assert.notNull(upgradeStrategy, "RequestUpgradeStrategy is required");
107 108 109 110 111
		this.upgradeStrategy = upgradeStrategy;
	}

	private static RequestUpgradeStrategy initUpgradeStrategy() {
		String className;
112 113 114 115 116 117 118 119 120
		if (tomcatPresent) {
			className = "TomcatRequestUpgradeStrategy";
		}
		else if (jettyPresent) {
			className = "JettyRequestUpgradeStrategy";
		}
		else if (undertowPresent) {
			className = "UndertowRequestUpgradeStrategy";
		}
121 122 123 124
		else if (reactorNettyPresent) {
			// As late as possible (Reactor Netty commonly used for WebClient)
			className = "ReactorNettyRequestUpgradeStrategy";
		}
125 126 127 128 129
		else {
			throw new IllegalStateException("No suitable default RequestUpgradeStrategy found");
		}

		try {
130
			className = "org.springframework.web.reactive.socket.server.upgrade." + className;
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
			Class<?> clazz = ClassUtils.forName(className, HandshakeWebSocketService.class.getClassLoader());
			return (RequestUpgradeStrategy) ReflectionUtils.accessibleConstructor(clazz).newInstance();
		}
		catch (Throwable ex) {
			throw new IllegalStateException(
					"Failed to instantiate RequestUpgradeStrategy: " + className, ex);
		}
	}


	/**
	 * Return the {@link RequestUpgradeStrategy} for WebSocket requests.
	 */
	public RequestUpgradeStrategy getUpgradeStrategy() {
		return this.upgradeStrategy;
	}

148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	/**
	 * Configure a predicate to use to extract
	 * {@link org.springframework.web.server.WebSession WebSession} attributes
	 * and use them to initialize the WebSocket session with.
	 * <p>By default this is not set in which case no attributes are passed.
	 * @param predicate the predicate
	 * @since 5.1
	 */
	public void setSessionAttributePredicate(@Nullable Predicate<String> predicate) {
		this.sessionAttributePredicate = predicate;
	}

	/**
	 * Return the configured predicate for initialization WebSocket session
	 * attributes from {@code WebSession} attributes.
	 * @since 5.1
	 */
	@Nullable
	public Predicate<String> getSessionAttributePredicate() {
		return this.sessionAttributePredicate;
	}

170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198

	@Override
	public void start() {
		if (!isRunning()) {
			this.running = true;
			doStart();
		}
	}

	protected void doStart() {
		if (getUpgradeStrategy() instanceof Lifecycle) {
			((Lifecycle) getUpgradeStrategy()).start();
		}
	}

	@Override
	public void stop() {
		if (isRunning()) {
			this.running = false;
			doStop();
		}
	}

	protected void doStop() {
		if (getUpgradeStrategy() instanceof Lifecycle) {
			((Lifecycle) getUpgradeStrategy()).stop();
		}
	}

199 200 201 202 203
	@Override
	public boolean isRunning() {
		return this.running;
	}

204 205

	@Override
206
	public Mono<Void> handleRequest(ServerWebExchange exchange, WebSocketHandler handler) {
207
		ServerHttpRequest request = exchange.getRequest();
R
Rossen Stoyanchev 已提交
208 209
		HttpMethod method = request.getMethod();
		HttpHeaders headers = request.getHeaders();
210

R
Rossen Stoyanchev 已提交
211
		if (HttpMethod.GET != method) {
212 213
			return Mono.error(new MethodNotAllowedException(
					request.getMethodValue(), Collections.singleton(HttpMethod.GET)));
214 215
		}

R
Rossen Stoyanchev 已提交
216 217
		if (!"WebSocket".equalsIgnoreCase(headers.getUpgrade())) {
			return handleBadRequest("Invalid 'Upgrade' header: " + headers);
218 219
		}

R
Rossen Stoyanchev 已提交
220
		List<String> connectionValue = headers.getConnection();
221
		if (!connectionValue.contains("Upgrade") && !connectionValue.contains("upgrade")) {
R
Rossen Stoyanchev 已提交
222
			return handleBadRequest("Invalid 'Connection' header: " + headers);
223
		}
R
Rossen Stoyanchev 已提交
224 225

		String key = headers.getFirst(SEC_WEBSOCKET_KEY);
226
		if (key == null) {
R
Rossen Stoyanchev 已提交
227 228 229
			return handleBadRequest("Missing \"Sec-WebSocket-Key\" header");
		}

230
		String protocol = selectProtocol(headers, handler);
231 232 233 234 235

		return initAttributes(exchange).flatMap(attributes ->
				this.upgradeStrategy.upgrade(exchange, handler, protocol,
						() -> createHandshakeInfo(exchange, request, protocol, attributes))
		);
R
Rossen Stoyanchev 已提交
236 237 238 239 240
	}

	private Mono<Void> handleBadRequest(String reason) {
		if (logger.isDebugEnabled()) {
			logger.debug(reason);
241
		}
R
Rossen Stoyanchev 已提交
242
		return Mono.error(new ServerWebInputException(reason));
243 244
	}

245
	@Nullable
246
	private String selectProtocol(HttpHeaders headers, WebSocketHandler handler) {
R
Rossen Stoyanchev 已提交
247
		String protocolHeader = headers.getFirst(SEC_WEBSOCKET_PROTOCOL);
248 249 250 251 252 253 254 255 256
		if (protocolHeader != null) {
			List<String> supportedProtocols = handler.getSubProtocols();
			for (String protocol : StringUtils.commaDelimitedListToStringArray(protocolHeader)) {
				if (supportedProtocols.contains(protocol)) {
					return protocol;
				}
			}
		}
		return null;
257 258
	}

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
	private Mono<Map<String, Object>> initAttributes(ServerWebExchange exchange) {
		if (this.sessionAttributePredicate == null) {
			return EMPTY_ATTRIBUTES;
		}
		return exchange.getSession().map(session ->
				session.getAttributes().entrySet().stream()
						.filter(entry -> this.sessionAttributePredicate.test(entry.getKey()))
						.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
	}

	private HandshakeInfo createHandshakeInfo(ServerWebExchange exchange, ServerHttpRequest request,
			@Nullable String protocol, Map<String, Object> attributes) {

		Mono<Principal> principal = exchange.getPrincipal();
		return new HandshakeInfo(request.getURI(), request.getHeaders(), principal, protocol, attributes);
	}

276
}