1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 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 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.catalina.valves;
import java.io.IOException;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.regex.Pattern;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpSession;
import jakarta.servlet.http.HttpSessionBindingEvent;
import jakarta.servlet.http.HttpSessionBindingListener;
import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
* Web crawlers can trigger the creation of many thousands of sessions as they crawl a site which may result in
* significant memory consumption. This Valve ensures that crawlers are associated with a single session - just like
* normal users - regardless of whether or not they provide a session token with their requests.
*/
public class CrawlerSessionManagerValve extends ValveBase {
private static final Log log = LogFactory.getLog(CrawlerSessionManagerValve.class);
private final Map<String,String> clientIdSessionId = new ConcurrentHashMap<>();
private String crawlerUserAgents = ".*[bB]ot.*|.*Yahoo! Slurp.*|.*Feedfetcher-Google.*";
private Pattern uaPattern = null;
private String crawlerIps = null;
private Pattern ipPattern = null;
private int sessionInactiveInterval = 60;
private boolean isHostAware = true;
private boolean isContextAware = true;
private Function<Request,String> clientIdentifierFunction = this::getClientIdentifier;
/**
* Specifies a default constructor so async support can be configured.
*/
public CrawlerSessionManagerValve() {
super(true);
}
/**
* Specify the regular expression (using {@link Pattern}) that will be used to identify crawlers based in the
* User-Agent header provided. The default is ".*GoogleBot.*|.*bingbot.*|.*Yahoo! Slurp.*"
*
* @param crawlerUserAgents The regular expression using {@link Pattern}
*/
public void setCrawlerUserAgents(String crawlerUserAgents) {
this.crawlerUserAgents = crawlerUserAgents;
if (crawlerUserAgents == null || crawlerUserAgents.isEmpty()) {
uaPattern = null;
} else {
uaPattern = Pattern.compile(crawlerUserAgents);
}
}
/**
* @see #setCrawlerUserAgents(String)
*
* @return The current regular expression being used to match user agents.
*/
public String getCrawlerUserAgents() {
return crawlerUserAgents;
}
/**
* Specify the regular expression (using {@link Pattern}) that will be used to identify crawlers based on their IP
* address. The default is no crawler IPs.
*
* @param crawlerIps The regular expression using {@link Pattern}
*/
public void setCrawlerIps(String crawlerIps) {
this.crawlerIps = crawlerIps;
if (crawlerIps == null || crawlerIps.isEmpty()) {
ipPattern = null;
} else {
ipPattern = Pattern.compile(crawlerIps);
}
}
/**
* @see #setCrawlerIps(String)
*
* @return The current regular expression being used to match IP addresses.
*/
public String getCrawlerIps() {
return crawlerIps;
}
/**
* Specify the session timeout (in seconds) for a crawler's session. This is typically lower than that for a user
* session. The default is 60 seconds.
*
* @param sessionInactiveInterval The new timeout for crawler sessions
*/
public void setSessionInactiveInterval(int sessionInactiveInterval) {
this.sessionInactiveInterval = sessionInactiveInterval;
}
/**
* @see #setSessionInactiveInterval(int)
*
* @return The current timeout in seconds
*/
public int getSessionInactiveInterval() {
return sessionInactiveInterval;
}
public Map<String,String> getClientIpSessionId() {
return clientIdSessionId;
}
public boolean isHostAware() {
return isHostAware;
}
public void setHostAware(boolean isHostAware) {
this.isHostAware = isHostAware;
}
public boolean isContextAware() {
return isContextAware;
}
public void setContextAware(boolean isContextAware) {
this.isContextAware = isContextAware;
}
/**
* Specify the clientIdentifier function that will be used to identify unique clients. The default is to use the
* client IP address, optionally combined with the host name and context name.
*
* @param clientIdentifierFunction The new function used to build identifiers for clients.
*/
public void setClientIdentifierFunction(Function<Request,String> clientIdentifierFunction) {
this.clientIdentifierFunction = clientIdentifierFunction;
}
@Override
protected void initInternal() throws LifecycleException {
super.initInternal();
uaPattern = Pattern.compile(crawlerUserAgents);
}
@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
Host host = request.getHost();
if (host == null) {
// Request will have no session
getNext().invoke(request, response);
return;
}
boolean isBot = false;
String sessionId = null;
String clientIp = request.getRemoteAddr();
String clientIdentifier = clientIdentifierFunction.apply(request);
if (log.isTraceEnabled()) {
log.trace(request.hashCode() + ": ClientIdentifier=" + clientIdentifier + ", RequestedSessionId=" +
request.getRequestedSessionId());
}
// If the incoming request has a valid session ID, no action is required
if (request.getSession(false) == null) {
// Is this a crawler - check the UA headers
Enumeration<String> uaHeaders = request.getHeaders("user-agent");
String uaHeader = null;
if (uaHeaders.hasMoreElements()) {
uaHeader = uaHeaders.nextElement();
}
// If more than one UA header - assume not a bot
if (uaHeader != null && !uaHeaders.hasMoreElements()) {
if (log.isTraceEnabled()) {
log.trace(request.hashCode() + ": UserAgent=" + uaHeader);
}
if (uaPattern.matcher(uaHeader).matches()) {
isBot = true;
if (log.isTraceEnabled()) {
log.trace(request.hashCode() + ": Bot found. UserAgent=" + uaHeader);
}
}
}
if (ipPattern != null && ipPattern.matcher(clientIp).matches()) {
isBot = true;
if (log.isTraceEnabled()) {
log.trace(request.hashCode() + ": Bot found. IP=" + clientIp);
}
}
// If this is a bot, is the session ID known?
if (isBot) {
sessionId = clientIdSessionId.get(clientIdentifier);
if (sessionId != null) {
request.setRequestedSessionId(sessionId);
if (log.isTraceEnabled()) {
log.trace(request.hashCode() + ": SessionID=" + sessionId);
}
}
}
}
getNext().invoke(request, response);
if (isBot) {
if (sessionId == null) {
// Has bot just created a session, if so make a note of it
HttpSession s = request.getSession(false);
if (s != null) {
clientIdSessionId.put(clientIdentifier, s.getId());
// #valueUnbound() will be called on session expiration
s.setAttribute(this.getClass().getName(),
new CrawlerHttpSessionBindingListener(clientIdSessionId, clientIdentifier));
s.setMaxInactiveInterval(sessionInactiveInterval);
if (log.isTraceEnabled()) {
log.trace(request.hashCode() + ": New bot session. SessionID=" + s.getId());
}
}
} else {
if (log.isTraceEnabled()) {
log.trace(request.hashCode() + ": Bot session accessed. SessionID=" + sessionId);
}
}
}
}
private String getClientIdentifier(Request request) {
StringBuilder result = new StringBuilder(request.getRemoteAddr());
if (isHostAware) {
result.append('-').append(request.getHost().getName());
}
Context context = request.getContext();
if (isContextAware && context != null) {
result.append(context.getName());
}
return result.toString();
}
private static class CrawlerHttpSessionBindingListener implements HttpSessionBindingListener, Serializable {
private static final long serialVersionUID = 1L;
private final transient Map<String,String> clientIdSessionId;
private final transient String clientIdentifier;
private CrawlerHttpSessionBindingListener(Map<String,String> clientIdSessionId, String clientIdentifier) {
this.clientIdSessionId = clientIdSessionId;
this.clientIdentifier = clientIdentifier;
}
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
if (clientIdentifier != null && clientIdSessionId != null) {
clientIdSessionId.remove(clientIdentifier, event.getSession().getId());
}
}
}
}
|