/
ServletWebRequest.java
438 lines (384 loc) · 12.6 KB
/
ServletWebRequest.java
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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
/*
* Copyright 2002-2022 the original author or authors.
*
* 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
*
* https://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.springframework.web.context.request;
import java.security.Principal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
/**
* {@link WebRequest} adapter for an {@link jakarta.servlet.http.HttpServletRequest}.
*
* @author Juergen Hoeller
* @author Brian Clozel
* @author Markus Malkusch
* @since 2.0
*/
public class ServletWebRequest extends ServletRequestAttributes implements NativeWebRequest {
private static final Set<String> SAFE_METHODS = Set.of("GET", "HEAD");
/**
* Pattern matching ETag multiple field values in headers such as "If-Match", "If-None-Match".
* @see <a href="https://tools.ietf.org/html/rfc7232#section-2.3">Section 2.3 of RFC 7232</a>
*/
private static final Pattern ETAG_HEADER_VALUE_PATTERN = Pattern.compile("\\*|\\s*((W\\/)?(\"[^\"]*\"))\\s*,?");
/**
* Date formats as specified in the HTTP RFC.
* @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a>
*/
private static final String[] DATE_FORMATS = new String[] {
"EEE, dd MMM yyyy HH:mm:ss zzz",
"EEE, dd-MMM-yy HH:mm:ss zzz",
"EEE MMM dd HH:mm:ss yyyy"
};
private static final TimeZone GMT = TimeZone.getTimeZone("GMT");
private boolean notModified = false;
/**
* Create a new ServletWebRequest instance for the given request.
* @param request current HTTP request
*/
public ServletWebRequest(HttpServletRequest request) {
super(request);
}
/**
* Create a new ServletWebRequest instance for the given request/response pair.
* @param request current HTTP request
* @param response current HTTP response (for automatic last-modified handling)
*/
public ServletWebRequest(HttpServletRequest request, @Nullable HttpServletResponse response) {
super(request, response);
}
@Override
public Object getNativeRequest() {
return getRequest();
}
@Override
public Object getNativeResponse() {
return getResponse();
}
@Override
public <T> T getNativeRequest(@Nullable Class<T> requiredType) {
return WebUtils.getNativeRequest(getRequest(), requiredType);
}
@Override
public <T> T getNativeResponse(@Nullable Class<T> requiredType) {
HttpServletResponse response = getResponse();
return (response != null ? WebUtils.getNativeResponse(response, requiredType) : null);
}
/**
* Return the HTTP method of the request.
* @since 4.0.2
*/
public HttpMethod getHttpMethod() {
return HttpMethod.valueOf(getRequest().getMethod());
}
@Override
@Nullable
public String getHeader(String headerName) {
return getRequest().getHeader(headerName);
}
@Override
@Nullable
public String[] getHeaderValues(String headerName) {
String[] headerValues = StringUtils.toStringArray(getRequest().getHeaders(headerName));
return (!ObjectUtils.isEmpty(headerValues) ? headerValues : null);
}
@Override
public Iterator<String> getHeaderNames() {
return CollectionUtils.toIterator(getRequest().getHeaderNames());
}
@Override
@Nullable
public String getParameter(String paramName) {
return getRequest().getParameter(paramName);
}
@Override
@Nullable
public String[] getParameterValues(String paramName) {
return getRequest().getParameterValues(paramName);
}
@Override
public Iterator<String> getParameterNames() {
return CollectionUtils.toIterator(getRequest().getParameterNames());
}
@Override
public Map<String, String[]> getParameterMap() {
return getRequest().getParameterMap();
}
@Override
public Locale getLocale() {
return getRequest().getLocale();
}
@Override
public String getContextPath() {
return getRequest().getContextPath();
}
@Override
@Nullable
public String getRemoteUser() {
return getRequest().getRemoteUser();
}
@Override
@Nullable
public Principal getUserPrincipal() {
return getRequest().getUserPrincipal();
}
@Override
public boolean isUserInRole(String role) {
return getRequest().isUserInRole(role);
}
@Override
public boolean isSecure() {
return getRequest().isSecure();
}
@Override
public boolean checkNotModified(long lastModifiedTimestamp) {
return checkNotModified(null, lastModifiedTimestamp);
}
@Override
public boolean checkNotModified(String etag) {
return checkNotModified(etag, -1);
}
@Override
public boolean checkNotModified(@Nullable String eTag, long lastModifiedTimestamp) {
HttpServletResponse response = getResponse();
if (this.notModified || (response != null && HttpStatus.OK.value() != response.getStatus())) {
return this.notModified;
}
// Evaluate conditions in order of precedence.
// See https://datatracker.ietf.org/doc/html/rfc9110#section-13.2.2
if (validateIfMatch(eTag)) {
updateResponseStateChanging(eTag, lastModifiedTimestamp);
return this.notModified;
}
// 2) If-Unmodified-Since
else if (validateIfUnmodifiedSince(lastModifiedTimestamp)) {
updateResponseStateChanging(eTag, lastModifiedTimestamp);
return this.notModified;
}
// 3) If-None-Match
if (!validateIfNoneMatch(eTag)) {
// 4) If-Modified-Since
validateIfModifiedSince(lastModifiedTimestamp);
}
updateResponseIdempotent(eTag, lastModifiedTimestamp);
return this.notModified;
}
private boolean validateIfMatch(@Nullable String eTag) {
if (SAFE_METHODS.contains(getRequest().getMethod())) {
return false;
}
Enumeration<String> ifMatchHeaders = getRequest().getHeaders(HttpHeaders.IF_MATCH);
if (!ifMatchHeaders.hasMoreElements()) {
return false;
}
this.notModified = matchRequestedETags(ifMatchHeaders, eTag, false);
return true;
}
private boolean validateIfNoneMatch(@Nullable String eTag) {
Enumeration<String> ifNoneMatchHeaders = getRequest().getHeaders(HttpHeaders.IF_NONE_MATCH);
if (!ifNoneMatchHeaders.hasMoreElements()) {
return false;
}
this.notModified = !matchRequestedETags(ifNoneMatchHeaders, eTag, true);
return true;
}
private boolean matchRequestedETags(Enumeration<String> requestedETags, @Nullable String eTag, boolean weakCompare) {
eTag = padEtagIfNecessary(eTag);
while (requestedETags.hasMoreElements()) {
// Compare weak/strong ETags as per https://datatracker.ietf.org/doc/html/rfc9110#section-8.8.3
Matcher eTagMatcher = ETAG_HEADER_VALUE_PATTERN.matcher(requestedETags.nextElement());
while (eTagMatcher.find()) {
// only consider "lost updates" checks for unsafe HTTP methods
if ("*".equals(eTagMatcher.group()) && StringUtils.hasLength(eTag)
&& !SAFE_METHODS.contains(getRequest().getMethod())) {
return false;
}
if (weakCompare) {
if (eTagWeakMatch(eTag, eTagMatcher.group(1))) {
return false;
}
}
else {
if (eTagStrongMatch(eTag, eTagMatcher.group(1))) {
return false;
}
}
}
}
return true;
}
@Nullable
private String padEtagIfNecessary(@Nullable String etag) {
if (!StringUtils.hasLength(etag)) {
return etag;
}
if ((etag.startsWith("\"") || etag.startsWith("W/\"")) && etag.endsWith("\"")) {
return etag;
}
return "\"" + etag + "\"";
}
private boolean eTagStrongMatch(@Nullable String first, @Nullable String second) {
if (!StringUtils.hasLength(first) || first.startsWith("W/")) {
return false;
}
return first.equals(second);
}
private boolean eTagWeakMatch(@Nullable String first, @Nullable String second) {
if (!StringUtils.hasLength(first) || !StringUtils.hasLength(second)) {
return false;
}
if (first.startsWith("W/")) {
first = first.substring(2);
}
if (second.startsWith("W/")) {
second = second.substring(2);
}
return first.equals(second);
}
private void updateResponseStateChanging(@Nullable String eTag, long lastModifiedTimestamp) {
if (this.notModified && getResponse() != null) {
getResponse().setStatus(HttpStatus.PRECONDITION_FAILED.value());
}
else {
addCachingResponseHeaders(eTag, lastModifiedTimestamp);
}
}
private boolean validateIfUnmodifiedSince(long lastModifiedTimestamp) {
if (lastModifiedTimestamp < 0) {
return false;
}
long ifUnmodifiedSince = parseDateHeader(HttpHeaders.IF_UNMODIFIED_SINCE);
if (ifUnmodifiedSince == -1) {
return false;
}
this.notModified = (ifUnmodifiedSince < (lastModifiedTimestamp / 1000 * 1000));
return true;
}
private void validateIfModifiedSince(long lastModifiedTimestamp) {
if (lastModifiedTimestamp < 0) {
return;
}
long ifModifiedSince = parseDateHeader(HttpHeaders.IF_MODIFIED_SINCE);
if (ifModifiedSince != -1) {
// We will perform this validation...
this.notModified = ifModifiedSince >= (lastModifiedTimestamp / 1000 * 1000);
}
}
private void updateResponseIdempotent(@Nullable String eTag, long lastModifiedTimestamp) {
if (getResponse() != null) {
boolean isHttpGetOrHead = SAFE_METHODS.contains(getRequest().getMethod());
if (this.notModified) {
getResponse().setStatus(isHttpGetOrHead ?
HttpStatus.NOT_MODIFIED.value() : HttpStatus.PRECONDITION_FAILED.value());
}
addCachingResponseHeaders(eTag, lastModifiedTimestamp);
}
}
private void addCachingResponseHeaders(@Nullable String eTag, long lastModifiedTimestamp) {
if (SAFE_METHODS.contains(getRequest().getMethod())) {
if (lastModifiedTimestamp > 0 && parseDateValue(getResponse().getHeader(HttpHeaders.LAST_MODIFIED)) == -1) {
getResponse().setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedTimestamp);
}
if (StringUtils.hasLength(eTag) && getResponse().getHeader(HttpHeaders.ETAG) == null) {
getResponse().setHeader(HttpHeaders.ETAG, padEtagIfNecessary(eTag));
}
}
}
public boolean isNotModified() {
return this.notModified;
}
private long parseDateHeader(String headerName) {
long dateValue = -1;
try {
dateValue = getRequest().getDateHeader(headerName);
}
catch (IllegalArgumentException ex) {
String headerValue = getHeader(headerName);
// Possibly an IE 10 style value: "Wed, 09 Apr 2014 09:57:42 GMT; length=13774"
if (headerValue != null) {
int separatorIndex = headerValue.indexOf(';');
if (separatorIndex != -1) {
String datePart = headerValue.substring(0, separatorIndex);
dateValue = parseDateValue(datePart);
}
}
}
return dateValue;
}
private long parseDateValue(@Nullable String headerValue) {
if (headerValue == null) {
// No header value sent at all
return -1;
}
if (headerValue.length() >= 3) {
// Short "0" or "-1" like values are never valid HTTP date headers...
// Let's only bother with SimpleDateFormat parsing for long enough values.
for (String dateFormat : DATE_FORMATS) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);
simpleDateFormat.setTimeZone(GMT);
try {
return simpleDateFormat.parse(headerValue).getTime();
}
catch (ParseException ex) {
// ignore
}
}
}
return -1;
}
@Override
public String getDescription(boolean includeClientInfo) {
HttpServletRequest request = getRequest();
StringBuilder sb = new StringBuilder();
sb.append("uri=").append(request.getRequestURI());
if (includeClientInfo) {
String client = request.getRemoteAddr();
if (StringUtils.hasLength(client)) {
sb.append(";client=").append(client);
}
HttpSession session = request.getSession(false);
if (session != null) {
sb.append(";session=").append(session.getId());
}
String user = request.getRemoteUser();
if (StringUtils.hasLength(user)) {
sb.append(";user=").append(user);
}
}
return sb.toString();
}
@Override
public String toString() {
return "ServletWebRequest: " + getDescription(true);
}
}