/
Request.java
2600 lines (2302 loc) · 85.1 KB
/
Request.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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package org.eclipse.jetty.server;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncListener;
import javax.servlet.DispatcherType;
import javax.servlet.MultipartConfigElement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestWrapper;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.Part;
import javax.servlet.http.PushBuilder;
import javax.servlet.http.WebConnection;
import org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.ComplianceViolation;
import org.eclipse.jetty.http.HostPortHttpField;
import org.eclipse.jetty.http.HttpCompliance;
import org.eclipse.jetty.http.HttpCookie;
import org.eclipse.jetty.http.HttpCookie.SetCookieHttpField;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpHeaderValue;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpScheme;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.http.HttpURI;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MetaData;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http.UriCompliance;
import org.eclipse.jetty.io.Connection;
import org.eclipse.jetty.io.RuntimeIOException;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.server.handler.ContextHandler.Context;
import org.eclipse.jetty.server.session.Session;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.Attributes;
import org.eclipse.jetty.util.AttributesMap;
import org.eclipse.jetty.util.HostPort;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.MultiMap;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.UrlEncoded;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Jetty Request.
* <p>
* Implements {@link javax.servlet.http.HttpServletRequest} from the <code>javax.servlet.http</code> package.
* </p>
* <p>
* The standard interface of mostly getters, is extended with setters so that the request is mutable by the handlers that it is passed to. This allows the
* request object to be as lightweight as possible and not actually implement any significant behavior. For example
* <ul>
*
* <li>the {@link Request#getContextPath()} method will return null, until the request has been passed to a {@link ContextHandler} which matches the
* {@link Request#getPathInfo()} with a context path and calls {@link Request#setContext(Context,String)} as a result. For
* some dispatch types (ie include and named dispatch) the context path may not reflect the {@link ServletContext} set
* by {@link Request#setContext(Context, String)}.</li>
*
* <li>the HTTP session methods will all return null sessions until such time as a request has been passed to a
* {@link org.eclipse.jetty.server.session.SessionHandler} which checks for session cookies and enables the ability to create new sessions.</li>
*
* <li>The {@link Request#getServletPath()} method will return "" until the request has been passed to a <code>org.eclipse.jetty.servlet.ServletHandler</code>
* and the pathInfo matched against the servlet URL patterns and {@link Request#setServletPathMapping(ServletPathMapping)} called as a result.</li>
* </ul>
*
* <p>
* A request instance is created for each connection accepted by the server and recycled for each HTTP request received via that connection.
* An effort is made to avoid reparsing headers and cookies that are likely to be the same for requests from the same connection.
* </p>
* <p>
* Request instances are recycled, which combined with badly written asynchronous applications can result in calls on requests that have been reset.
* The code is written in a style to avoid NPE and ISE when such calls are made, as this has often proved generate exceptions that distraction
* from debugging such bad asynchronous applications. Instead, request methods attempt to not fail when called in an illegal state, so that hopefully
* the bad application will proceed to a major state event (eg calling AsyncContext.onComplete) which has better asynchronous guards, true atomic state
* and better failure behaviour that will assist in debugging.
* </p>
* <p>
* The form content that a request can process is limited to protect from Denial of Service attacks. The size in bytes is limited by
* {@link ContextHandler#getMaxFormContentSize()} or if there is no context then the "org.eclipse.jetty.server.Request.maxFormContentSize" {@link Server}
* attribute. The number of parameters keys is limited by {@link ContextHandler#getMaxFormKeys()} or if there is no context then the
* "org.eclipse.jetty.server.Request.maxFormKeys" {@link Server} attribute.
* </p>
* <p>If IOExceptions or timeouts occur while reading form parameters, these are thrown as unchecked Exceptions: ether {@link RuntimeIOException},
* {@link BadMessageException} or {@link RuntimeException} as appropriate.</p>
*/
public class Request implements HttpServletRequest
{
public static final String __MULTIPART_CONFIG_ELEMENT = "org.eclipse.jetty.multipartConfig";
private static final Logger LOG = LoggerFactory.getLogger(Request.class);
private static final Collection<Locale> __defaultLocale = Collections.singleton(Locale.getDefault());
private static final int INPUT_NONE = 0;
private static final int INPUT_STREAM = 1;
private static final int INPUT_READER = 2;
private static final MultiMap<String> NO_PARAMS = new MultiMap<>();
private static final MultiMap<String> BAD_PARAMS = new MultiMap<>();
/**
* Compare inputParameters to NO_PARAMS by Reference
*
* @param inputParameters The parameters to compare to NO_PARAMS
* @return True if the inputParameters reference is equal to NO_PARAMS otherwise False
*/
private static boolean isNoParams(MultiMap<String> inputParameters)
{
@SuppressWarnings("ReferenceEquality")
boolean isNoParams = (inputParameters == NO_PARAMS);
return isNoParams;
}
/**
* Obtain the base {@link Request} instance of a {@link ServletRequest}, by
* coercion, unwrapping or special attribute.
*
* @param request The request
* @return the base {@link Request} instance of a {@link ServletRequest}.
*/
public static Request getBaseRequest(ServletRequest request)
{
if (request instanceof Request)
return (Request)request;
Object channel = request.getAttribute(HttpChannel.class.getName());
if (channel instanceof HttpChannel)
return ((HttpChannel)channel).getRequest();
while (request instanceof ServletRequestWrapper)
{
request = ((ServletRequestWrapper)request).getRequest();
}
if (request instanceof Request)
return (Request)request;
return null;
}
private final HttpChannel _channel;
private final List<ServletRequestAttributeListener> _requestAttributeListeners = new ArrayList<>();
private final HttpInput _input;
private MetaData.Request _metaData;
private HttpFields _httpFields;
private HttpFields _trailers;
private HttpURI _uri;
private String _method;
private String _pathInContext;
private ServletPathMapping _servletPathMapping;
private Object _asyncNotSupportedSource = null;
private boolean _secure;
private boolean _newContext;
private boolean _cookiesExtracted = false;
private boolean _handled = false;
private boolean _contentParamsExtracted;
private boolean _requestedSessionIdFromCookie = false;
private Attributes _attributes;
private Authentication _authentication;
private String _contentType;
private String _characterEncoding;
private ContextHandler.Context _context;
private ContextHandler.Context _errorContext;
private Cookies _cookies;
private DispatcherType _dispatcherType;
private int _inputState = INPUT_NONE;
private BufferedReader _reader;
private String _readerEncoding;
private MultiMap<String> _queryParameters;
private MultiMap<String> _contentParameters;
private MultiMap<String> _parameters;
private Charset _queryEncoding;
private InetSocketAddress _remote;
private String _requestedSessionId;
private UserIdentity.Scope _scope;
private HttpSession _session;
private SessionHandler _sessionHandler;
private long _timeStamp;
private MultiPartFormInputStream _multiParts; //if the request is a multi-part mime
private AsyncContextState _async;
private List<Session> _sessions; //list of sessions used during lifetime of request
public Request(HttpChannel channel, HttpInput input)
{
_channel = channel;
_input = input;
}
public HttpFields getHttpFields()
{
return _httpFields;
}
public void setHttpFields(HttpFields fields)
{
_httpFields = fields.asImmutable();
}
@Override
public Map<String, String> getTrailerFields()
{
HttpFields trailersFields = getTrailerHttpFields();
if (trailersFields == null)
return Collections.emptyMap();
Map<String, String> trailers = new HashMap<>();
for (HttpField field : trailersFields)
{
String key = field.getName().toLowerCase();
String value = trailers.get(key);
trailers.put(key, value == null ? field.getValue() : value + "," + field.getValue());
}
return trailers;
}
public void setTrailerHttpFields(HttpFields trailers)
{
_trailers = trailers == null ? null : trailers.asImmutable();
}
public HttpFields getTrailerHttpFields()
{
return _trailers;
}
public HttpInput getHttpInput()
{
return _input;
}
public boolean isPush()
{
return Boolean.TRUE.equals(getAttribute("org.eclipse.jetty.pushed"));
}
public boolean isPushSupported()
{
return !isPush() && getHttpChannel().getHttpTransport().isPushSupported();
}
private static final EnumSet<HttpHeader> NOT_PUSHED_HEADERS = EnumSet.of(
HttpHeader.IF_MATCH,
HttpHeader.IF_RANGE,
HttpHeader.IF_UNMODIFIED_SINCE,
HttpHeader.RANGE,
HttpHeader.EXPECT,
HttpHeader.REFERER,
HttpHeader.COOKIE,
HttpHeader.AUTHORIZATION,
HttpHeader.IF_NONE_MATCH,
HttpHeader.IF_MODIFIED_SINCE
);
@Override
public PushBuilder newPushBuilder()
{
if (!isPushSupported())
return null;
HttpFields.Mutable fields = HttpFields.build(getHttpFields(), NOT_PUSHED_HEADERS);
HttpField authField = getHttpFields().getField(HttpHeader.AUTHORIZATION);
//TODO check what to do for digest etc etc
if (authField != null && getUserPrincipal() != null && authField.getValue().startsWith("Basic"))
fields.add(authField);
String id;
try
{
HttpSession session = getSession();
if (session != null)
{
session.getLastAccessedTime(); // checks if session is valid
id = session.getId();
}
else
id = getRequestedSessionId();
}
catch (IllegalStateException e)
{
id = getRequestedSessionId();
}
Map<String, String> cookies = new HashMap<>();
Cookie[] existingCookies = getCookies();
if (existingCookies != null)
{
for (Cookie c: getCookies())
{
cookies.put(c.getName(), c.getValue());
}
}
//Any Set-Cookies that were set on the response must be set as Cookies on the
//PushBuilder, unless the max-age of the cookie is <= 0
HttpFields responseFields = getResponse().getHttpFields();
for (HttpField field : responseFields)
{
HttpHeader header = field.getHeader();
if (header == HttpHeader.SET_COOKIE)
{
HttpCookie cookie = ((SetCookieHttpField)field).getHttpCookie();
if (cookie.getMaxAge() > 0)
cookies.put(cookie.getName(), cookie.getValue());
else
cookies.remove(cookie.getName());
}
}
if (!cookies.isEmpty())
{
StringBuilder buff = new StringBuilder();
for (Map.Entry<String, String> entry : cookies.entrySet())
{
if (buff.length() > 0)
buff.append("; ");
buff.append(entry.getKey()).append('=').append(entry.getValue());
}
fields.add(new HttpField(HttpHeader.COOKIE, buff.toString()));
}
PushBuilder builder = new PushBuilderImpl(this, fields, getMethod(), getQueryString(), id);
builder.addHeader("referer", getRequestURL().toString());
return builder;
}
public void addEventListener(final EventListener listener)
{
if (listener instanceof ServletRequestAttributeListener)
_requestAttributeListeners.add((ServletRequestAttributeListener)listener);
if (listener instanceof AsyncListener)
throw new IllegalArgumentException(listener.getClass().toString());
}
/**
* Remember a session that this request has just entered.
*
* @param s the session
*/
public void enterSession(HttpSession s)
{
if (!(s instanceof Session))
return;
if (_sessions == null)
_sessions = new ArrayList<>();
if (LOG.isDebugEnabled())
LOG.debug("Request {} entering session={}", this, s);
_sessions.add((Session)s);
}
/**
* Complete this request's access to a session.
*
* @param session the session
*/
private void leaveSession(Session session)
{
if (LOG.isDebugEnabled())
LOG.debug("Request {} leaving session {}", this, session);
//try and scope to a request and context before leaving the session
ServletContext ctx = session.getServletContext();
ContextHandler handler = ContextHandler.getContextHandler(ctx);
if (handler == null)
session.getSessionHandler().complete(session);
else
handler.handle(this, () -> session.getSessionHandler().complete(session));
}
/**
* A response is being committed for a session,
* potentially write the session out before the
* client receives the response.
*
* @param session the session
*/
private void commitSession(Session session)
{
if (LOG.isDebugEnabled())
LOG.debug("Response {} committing for session {}", this, session);
//try and scope to a request and context before committing the session
ServletContext ctx = session.getServletContext();
ContextHandler handler = ContextHandler.getContextHandler(ctx);
if (handler == null)
session.getSessionHandler().commit(session);
else
handler.handle(this, () -> session.getSessionHandler().commit(session));
}
private MultiMap<String> getParameters()
{
if (!_contentParamsExtracted)
{
// content parameters need boolean protection as they can only be read
// once, but may be reset to null by a reset
_contentParamsExtracted = true;
// Extract content parameters; these cannot be replaced by a forward()
// once extracted and may have already been extracted by getParts() or
// by a processing happening after a form-based authentication.
if (_contentParameters == null)
{
try
{
extractContentParameters();
}
catch (IllegalStateException | IllegalArgumentException e)
{
LOG.warn(e.toString());
throw new BadMessageException("Unable to parse form content", e);
}
}
}
// Extract query string parameters; these may be replaced by a forward()
// and may have already been extracted by mergeQueryParameters().
if (_queryParameters == null)
extractQueryParameters();
// Do parameters need to be combined?
if (isNoParams(_queryParameters) || _queryParameters.size() == 0)
_parameters = _contentParameters;
else if (isNoParams(_contentParameters) || _contentParameters.size() == 0)
_parameters = _queryParameters;
else if (_parameters == null)
{
_parameters = new MultiMap<>();
_parameters.addAllValues(_queryParameters);
_parameters.addAllValues(_contentParameters);
}
// protect against calls to recycled requests (which is illegal, but
// this gives better failures
MultiMap<String> parameters = _parameters;
return parameters == null ? NO_PARAMS : parameters;
}
private void extractQueryParameters()
{
if (_uri == null || StringUtil.isEmpty(_uri.getQuery()))
_queryParameters = NO_PARAMS;
else
{
try
{
_queryParameters = new MultiMap<>();
UrlEncoded.decodeTo(_uri.getQuery(), _queryParameters, _queryEncoding);
}
catch (IllegalStateException | IllegalArgumentException e)
{
_queryParameters = BAD_PARAMS;
throw new BadMessageException("Unable to parse URI query", e);
}
}
}
private boolean isContentEncodingSupported()
{
String contentEncoding = getHttpFields().get(HttpHeader.CONTENT_ENCODING);
if (contentEncoding == null)
return true;
return HttpHeaderValue.IDENTITY.is(contentEncoding);
}
private void extractContentParameters()
{
String contentType = getContentType();
if (contentType == null || contentType.isEmpty())
_contentParameters = NO_PARAMS;
else
{
_contentParameters = new MultiMap<>();
int contentLength = getContentLength();
if (contentLength != 0 && _inputState == INPUT_NONE)
{
String baseType = HttpField.valueParameters(contentType, null);
if (MimeTypes.Type.FORM_ENCODED.is(baseType) &&
_channel.getHttpConfiguration().isFormEncodedMethod(getMethod()))
{
if (_metaData != null && !isContentEncodingSupported())
{
throw new BadMessageException(HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, "Unsupported Content-Encoding");
}
extractFormParameters(_contentParameters);
}
else if (MimeTypes.Type.MULTIPART_FORM_DATA.is(baseType) &&
getAttribute(__MULTIPART_CONFIG_ELEMENT) != null &&
_multiParts == null)
{
try
{
if (_metaData != null && !isContentEncodingSupported())
{
throw new BadMessageException(HttpStatus.UNSUPPORTED_MEDIA_TYPE_415, "Unsupported Content-Encoding");
}
getParts(_contentParameters);
}
catch (IOException e)
{
String msg = "Unable to extract content parameters";
if (LOG.isDebugEnabled())
LOG.debug(msg, e);
throw new RuntimeIOException(msg, e);
}
}
}
}
}
public void extractFormParameters(MultiMap<String> params)
{
try
{
int maxFormContentSize = ContextHandler.DEFAULT_MAX_FORM_CONTENT_SIZE;
int maxFormKeys = ContextHandler.DEFAULT_MAX_FORM_KEYS;
if (_context != null)
{
ContextHandler contextHandler = _context.getContextHandler();
maxFormContentSize = contextHandler.getMaxFormContentSize();
maxFormKeys = contextHandler.getMaxFormKeys();
}
else
{
maxFormContentSize = lookupServerAttribute(ContextHandler.MAX_FORM_CONTENT_SIZE_KEY, maxFormContentSize);
maxFormKeys = lookupServerAttribute(ContextHandler.MAX_FORM_KEYS_KEY, maxFormKeys);
}
int contentLength = getContentLength();
if (maxFormContentSize >= 0 && contentLength > maxFormContentSize)
throw new IllegalStateException("Form is larger than max length " + maxFormContentSize);
InputStream in = getInputStream();
if (_input.isAsync())
throw new IllegalStateException("Cannot extract parameters with async IO");
UrlEncoded.decodeTo(in, params, getCharacterEncoding(), maxFormContentSize, maxFormKeys);
}
catch (IOException e)
{
String msg = "Unable to extract form parameters";
if (LOG.isDebugEnabled())
LOG.debug(msg, e);
throw new RuntimeIOException(msg, e);
}
}
private int lookupServerAttribute(String key, int dftValue)
{
Object attribute = _channel.getServer().getAttribute(key);
if (attribute instanceof Number)
return ((Number)attribute).intValue();
else if (attribute instanceof String)
return Integer.parseInt((String)attribute);
return dftValue;
}
@Override
public AsyncContext getAsyncContext()
{
HttpChannelState state = getHttpChannelState();
if (_async == null || !state.isAsyncStarted())
throw new IllegalStateException(state.getStatusString());
return _async;
}
public HttpChannelState getHttpChannelState()
{
return _channel.getState();
}
public ComplianceViolation.Listener getComplianceViolationListener()
{
if (_channel instanceof ComplianceViolation.Listener)
{
return (ComplianceViolation.Listener)_channel;
}
ComplianceViolation.Listener listener = _channel.getConnector().getBean(ComplianceViolation.Listener.class);
if (listener == null)
{
listener = _channel.getServer().getBean(ComplianceViolation.Listener.class);
}
return listener;
}
/**
* Get Request Attribute.
* <p>
* Also supports jetty specific attributes to gain access to Jetty APIs:
* <dl>
* <dt>org.eclipse.jetty.server.Server</dt><dd>The Jetty Server instance</dd>
* <dt>org.eclipse.jetty.server.HttpChannel</dt><dd>The HttpChannel for this request</dd>
* <dt>org.eclipse.jetty.server.HttpConnection</dt><dd>The HttpConnection or null if another transport is used</dd>
* </dl>
* While these attributes may look like security problems, they are exposing nothing that is not already
* available via reflection from a Request instance.
*
* @see javax.servlet.ServletRequest#getAttribute(java.lang.String)
*/
@Override
public Object getAttribute(String name)
{
if (name.startsWith("org.eclipse.jetty"))
{
if (Server.class.getName().equals(name))
return _channel.getServer();
if (HttpChannel.class.getName().equals(name))
return _channel;
if (HttpConnection.class.getName().equals(name) &&
_channel.getHttpTransport() instanceof HttpConnection)
return _channel.getHttpTransport();
}
return (_attributes == null) ? null : _attributes.getAttribute(name);
}
@Override
public Enumeration<String> getAttributeNames()
{
if (_attributes == null)
return Collections.enumeration(Collections.emptyList());
return AttributesMap.getAttributeNamesCopy(_attributes);
}
public Attributes getAttributes()
{
if (_attributes == null)
_attributes = new ServletAttributes();
return _attributes;
}
/**
* Get the authentication.
*
* @return the authentication
*/
public Authentication getAuthentication()
{
return _authentication;
}
@Override
public String getAuthType()
{
if (_authentication instanceof Authentication.Deferred)
setAuthentication(((Authentication.Deferred)_authentication).authenticate(this));
if (_authentication instanceof Authentication.User)
return ((Authentication.User)_authentication).getAuthMethod();
return null;
}
@Override
public String getCharacterEncoding()
{
if (_characterEncoding == null)
{
if (_context != null)
_characterEncoding = _context.getRequestCharacterEncoding();
if (_characterEncoding == null)
{
String contentType = getContentType();
if (contentType != null)
{
MimeTypes.Type mime = MimeTypes.CACHE.get(contentType);
String charset = (mime == null || mime.getCharset() == null) ? MimeTypes.getCharsetFromContentType(contentType) : mime.getCharset().toString();
if (charset != null)
_characterEncoding = charset;
}
}
}
return _characterEncoding;
}
/**
* @return Returns the connection.
*/
public HttpChannel getHttpChannel()
{
return _channel;
}
@Override
public int getContentLength()
{
long contentLength = getContentLengthLong();
if (contentLength > Integer.MAX_VALUE)
// Per ServletRequest#getContentLength() javadoc this must return -1 for values exceeding Integer.MAX_VALUE
return -1;
return (int)contentLength;
}
@Override
public long getContentLengthLong()
{
// Even thought the metadata might know the real content length,
// we always look at the headers because the length may be changed by interceptors.
if (_httpFields == null)
return -1;
return _httpFields.getLongField(HttpHeader.CONTENT_LENGTH);
}
public long getContentRead()
{
return _input.getContentReceived();
}
@Override
public String getContentType()
{
if (_contentType == null)
{
MetaData.Request metadata = _metaData;
_contentType = metadata == null ? null : metadata.getFields().get(HttpHeader.CONTENT_TYPE);
}
return _contentType;
}
/**
* @return The current {@link Context context} used for this request, or <code>null</code> if {@link #setContext} has not yet been called.
*/
public Context getContext()
{
return _context;
}
/**
* @return The current {@link Context context} used for this error handling for this request. If the request is asynchronous,
* then it is the context that called async. Otherwise it is the last non-null context passed to #setContext
*/
public Context getErrorContext()
{
if (isAsyncStarted())
{
ContextHandler handler = _channel.getState().getContextHandler();
if (handler != null)
return handler.getServletContext();
}
return _errorContext;
}
@Override
public String getContextPath()
{
// The context path returned is normally for the current context. Except during a cross context
// INCLUDE dispatch, in which case this method returns the context path of the source context,
// which we recover from the IncludeAttributes wrapper.
Context context;
if (_dispatcherType == DispatcherType.INCLUDE)
{
Dispatcher.IncludeAttributes include = Attributes.unwrap(_attributes, Dispatcher.IncludeAttributes.class);
context = (include == null) ? _context : include.getSourceContext();
}
else
{
context = _context;
}
if (context == null)
return null;
return context.getContextHandler().getRequestContextPath();
}
/** Get the path in the context.
*
* The path relative to the context path, analogous to {@link #getServletPath()} + {@link #getPathInfo()}.
* If no context is set, then the path in context is the full path.
* @return The decoded part of the {@link #getRequestURI()} path after any {@link #getContextPath()}
* up to any {@link #getQueryString()}, excluding path parameters.
* @see #setContext(Context, String)
*/
public String getPathInContext()
{
return _pathInContext;
}
@Override
public Cookie[] getCookies()
{
MetaData.Request metadata = _metaData;
if (metadata == null || _cookiesExtracted)
{
if (_cookies == null || _cookies.getCookies().length == 0)
return null;
return _cookies.getCookies();
}
_cookiesExtracted = true;
for (HttpField field : metadata.getFields())
{
if (field.getHeader() == HttpHeader.COOKIE)
{
if (_cookies == null)
_cookies = new Cookies(getHttpChannel().getHttpConfiguration().getRequestCookieCompliance(), getComplianceViolationListener());
_cookies.addCookieField(field.getValue());
}
}
//Javadoc for Request.getCookies() stipulates null for no cookies
if (_cookies == null || _cookies.getCookies().length == 0)
return null;
return _cookies.getCookies();
}
@Override
public long getDateHeader(String name)
{
HttpFields fields = _httpFields;
return fields == null ? -1 : fields.getDateField(name);
}
@Override
public DispatcherType getDispatcherType()
{
return _dispatcherType;
}
@Override
public String getHeader(String name)
{
HttpFields fields = _httpFields;
return fields == null ? null : fields.get(name);
}
@Override
public Enumeration<String> getHeaderNames()
{
HttpFields fields = _httpFields;
return fields == null ? Collections.emptyEnumeration() : fields.getFieldNames();
}
@Override
public Enumeration<String> getHeaders(String name)
{
HttpFields fields = _httpFields;
if (fields == null)
return Collections.emptyEnumeration();
Enumeration<String> e = fields.getValues(name);
if (e == null)
return Collections.enumeration(Collections.emptyList());
return e;
}
/**
* @return Returns the inputState.
*/
public int getInputState()
{
return _inputState;
}
@Override
public ServletInputStream getInputStream() throws IOException
{
if (_inputState != INPUT_NONE && _inputState != INPUT_STREAM)
throw new IllegalStateException("READER");
_inputState = INPUT_STREAM;
if (_channel.isExpecting100Continue())
_channel.continue100(_input.available());
return _input;
}
@Override
public int getIntHeader(String name)
{
HttpFields fields = _httpFields;
return fields == null ? -1 : (int)fields.getLongField(name);
}
@Override
public Locale getLocale()
{
HttpFields fields = _httpFields;
if (fields == null)
return Locale.getDefault();
List<String> acceptable = fields.getQualityCSV(HttpHeader.ACCEPT_LANGUAGE);
// handle no locale
if (acceptable.isEmpty())
return Locale.getDefault();
String language = acceptable.get(0);
language = HttpField.stripParameters(language);
String country = "";
int dash = language.indexOf('-');
if (dash > -1)
{
country = language.substring(dash + 1).trim();
language = language.substring(0, dash).trim();
}
return new Locale(language, country);
}
@Override
public Enumeration<Locale> getLocales()
{
HttpFields fields = _httpFields;
if (fields == null)
return Collections.enumeration(__defaultLocale);
List<String> acceptable = fields.getQualityCSV(HttpHeader.ACCEPT_LANGUAGE);
// handle no locale
if (acceptable.isEmpty())
return Collections.enumeration(__defaultLocale);
List<Locale> locales = acceptable.stream().map(language ->
{
language = HttpField.stripParameters(language);
String country = "";
int dash = language.indexOf('-');
if (dash > -1)
{
country = language.substring(dash + 1).trim();
language = language.substring(0, dash).trim();
}
return new Locale(language, country);
}).collect(Collectors.toList());
return Collections.enumeration(locales);
}
@Override
public String getLocalAddr()
{
if (_channel != null)
{
InetSocketAddress local = _channel.getLocalAddress();
if (local == null)
return "";
InetAddress address = local.getAddress();