/
Request.java
2600 lines (2323 loc) · 81.9 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-2021 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
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.net.UnknownHostException;
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.Enumeration;
import java.util.EventListener;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Supplier;
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.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.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 org.eclipse.jetty.http.BadMessageException;
import org.eclipse.jetty.http.HostPortHttpField;
import org.eclipse.jetty.http.HttpComplianceSection;
import org.eclipse.jetty.http.HttpCookie;
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.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.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
/**
* 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#setContextPath(String)} as a result.</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 null 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#setServletPath(String)} 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";
public static final String MULTIPARTS = "org.eclipse.jetty.multiParts";
private static final Logger LOG = Log.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<>();
/**
* 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 String _originalURI;
private String _contextPath;
private String _servletPath;
private String _pathInfo;
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 CookieCutter _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 String _queryEncoding;
private InetSocketAddress _remote;
private String _requestedSessionId;
private UserIdentity.Scope _scope;
private HttpSession _session;
private SessionHandler _sessionHandler;
private long _timeStamp;
private MultiParts _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()
{
MetaData.Request metadata = _metaData;
return metadata == null ? null : metadata.getFields();
}
public HttpFields getTrailers()
{
MetaData.Request metadata = _metaData;
Supplier<HttpFields> trailers = metadata == null ? null : metadata.getTrailerSupplier();
return trailers == null ? null : trailers.get();
}
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();
}
/**
* Get a PushBuilder associated with this request initialized as follows:<ul>
* <li>The method is initialized to "GET"</li>
* <li>The headers from this request are copied to the Builder, except for:<ul>
* <li>Conditional headers (eg. If-Modified-Since)
* <li>Range headers
* <li>Expect headers
* <li>Authorization headers
* <li>Referrer headers
* </ul></li>
* <li>If the request was Authenticated, an Authorization header will
* be set with a container generated token that will result in equivalent
* Authorization</li>
* <li>The query string from {@link #getQueryString()}
* <li>The {@link #getRequestedSessionId()} value, unless at the time
* of the call {@link #getSession(boolean)}
* has previously been called to create a new {@link HttpSession}, in
* which case the new session ID will be used as the PushBuilders
* requested session ID.</li>
* <li>The source of the requested session id will be the same as for
* this request</li>
* <li>The builders Referer header will be set to {@link #getRequestURL()}
* plus any {@link #getQueryString()} </li>
* <li>If {@link HttpServletResponse#addCookie(Cookie)} has been called
* on the associated response, then a corresponding Cookie header will be added
* to the PushBuilder, unless the {@link Cookie#getMaxAge()} is <=0, in which
* case the Cookie will be removed from the builder.</li>
* <li>If this request has has the conditional headers If-Modified-Since or
* If-None-Match then the {@link PushBuilderImpl#isConditional()} header is set
* to true.
* </ul>
*
* <p>Each call to getPushBuilder() will return a new instance
* of a PushBuilder based off this Request. Any mutations to the
* returned PushBuilder are not reflected on future returns.
*
* @return A new PushBuilder or null if push is not supported
*/
public PushBuilder getPushBuilder()
{
if (!isPushSupported())
return null;
HttpFields fields = new HttpFields(getHttpFields().size() + 5);
boolean conditional = false;
for (HttpField field : getHttpFields())
{
HttpHeader header = field.getHeader();
if (header == null)
fields.add(field);
else
{
switch (header)
{
case IF_MATCH:
case IF_RANGE:
case IF_UNMODIFIED_SINCE:
case RANGE:
case EXPECT:
case REFERER:
case COOKIE:
continue;
case AUTHORIZATION:
continue;
case IF_NONE_MATCH:
case IF_MODIFIED_SINCE:
conditional = true;
continue;
default:
fields.add(field);
}
}
}
String id = null;
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();
}
PushBuilder builder = new PushBuilderImpl(this, fields, getMethod(), getQueryString(), id, conditional);
builder.addHeader("referer", getRequestURL().toString());
// TODO process any set cookies
// TODO process any user_identity
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);
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);
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)
{
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)
{
try
{
extractQueryParameters();
}
catch (IllegalStateException | IllegalArgumentException e)
{
throw new BadMessageException("Unable to parse URI query", e);
}
}
// 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()
{
MetaData.Request metadata = _metaData;
if (metadata == null || metadata.getURI() == null || !metadata.getURI().hasQuery())
_queryParameters = NO_PARAMS;
else
{
_queryParameters = new MultiMap<>();
if (_queryEncoding == null)
metadata.getURI().decodeQueryTo(_queryParameters);
else
{
try
{
metadata.getURI().decodeQueryTo(_queryParameters, _queryEncoding);
}
catch (UnsupportedEncodingException e)
{
if (LOG.isDebugEnabled())
LOG.warn(e);
else
LOG.warn(e.toString());
}
}
}
}
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 = HttpFields.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)
{
LOG.debug(e);
throw new RuntimeIOException(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)
{
LOG.debug(e);
throw new RuntimeIOException(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();
}
/**
* 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);
}
/*
* @see javax.servlet.ServletRequest#getAttributeNames()
*/
@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;
}
/*
* @see javax.servlet.http.HttpServletRequest#getAuthType()
*/
@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;
}
/*
* @see javax.servlet.ServletRequest#getCharacterEncoding()
*/
@Override
public String getCharacterEncoding()
{
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;
}
/*
* @see javax.servlet.ServletRequest#getContentLength()
*/
@Override
public int getContentLength()
{
MetaData.Request metadata = _metaData;
if (metadata == null)
return -1;
long contentLength = metadata.getContentLength();
if (contentLength != Long.MIN_VALUE)
{
if (contentLength > Integer.MAX_VALUE)
{
// Per ServletRequest#getContentLength() javadoc this must return -1 for values exceeding Integer.MAX_VALUE
return -1;
}
else
{
return (int)contentLength;
}
}
return (int)metadata.getFields().getLongField(HttpHeader.CONTENT_LENGTH.asString());
}
/*
* @see javax.servlet.ServletRequest.getContentLengthLong()
*/
@Override
public long getContentLengthLong()
{
MetaData.Request metadata = _metaData;
if (metadata == null)
return -1L;
if (metadata.getContentLength() != Long.MIN_VALUE)
return metadata.getContentLength();
return metadata.getFields().getLongField(HttpHeader.CONTENT_LENGTH.asString());
}
public long getContentRead()
{
return _input.getContentConsumed();
}
/*
* @see javax.servlet.ServletRequest#getContentType()
*/
@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;
}
/*
* @see javax.servlet.http.HttpServletRequest#getContextPath()
*/
@Override
public String getContextPath()
{
return _contextPath;
}
/*
* @see javax.servlet.http.HttpServletRequest#getCookies()
*/
@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 CookieCutter(getHttpChannel().getHttpConfiguration().getRequestCookieCompliance());
_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();
}
/*
* @see javax.servlet.http.HttpServletRequest#getDateHeader(java.lang.String)
*/
@Override
public long getDateHeader(String name)
{
MetaData.Request metadata = _metaData;
return metadata == null ? -1 : metadata.getFields().getDateField(name);
}
@Override
public DispatcherType getDispatcherType()
{
return _dispatcherType;
}
/*
* @see javax.servlet.http.HttpServletRequest#getHeader(java.lang.String)
*/
@Override
public String getHeader(String name)
{
MetaData.Request metadata = _metaData;
return metadata == null ? null : metadata.getFields().get(name);
}
/*
* @see javax.servlet.http.HttpServletRequest#getHeaderNames()
*/
@Override
public Enumeration<String> getHeaderNames()
{
MetaData.Request metadata = _metaData;
return metadata == null ? Collections.emptyEnumeration() : metadata.getFields().getFieldNames();
}
/*
* @see javax.servlet.http.HttpServletRequest#getHeaders(java.lang.String)
*/
@Override
public Enumeration<String> getHeaders(String name)
{
MetaData.Request metadata = _metaData;
if (metadata == null)
return Collections.emptyEnumeration();
Enumeration<String> e = metadata.getFields().getValues(name);
if (e == null)
return Collections.enumeration(Collections.emptyList());
return e;
}
/**
* @return Returns the inputState.
*/
public int getInputState()
{
return _inputState;
}
/*
* @see javax.servlet.ServletRequest#getInputStream()
*/
@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;
}
/*
* @see javax.servlet.http.HttpServletRequest#getIntHeader(java.lang.String)
*/
@Override
public int getIntHeader(String name)
{
MetaData.Request metadata = _metaData;
return metadata == null ? -1 : (int)metadata.getFields().getLongField(name);
}
/*
* @see javax.servlet.ServletRequest#getLocale()
*/
@Override
public Locale getLocale()
{
MetaData.Request metadata = _metaData;
if (metadata == null)
return Locale.getDefault();
List<String> acceptable = metadata.getFields().getQualityCSV(HttpHeader.ACCEPT_LANGUAGE);
// handle no locale
if (acceptable.isEmpty())
return Locale.getDefault();
String language = acceptable.get(0);
language = HttpFields.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);
}
/*
* @see javax.servlet.ServletRequest#getLocales()
*/
@Override
public Enumeration<Locale> getLocales()
{
MetaData.Request metadata = _metaData;
if (metadata == null)
return Collections.enumeration(__defaultLocale);
List<String> acceptable = metadata.getFields().getQualityCSV(HttpHeader.ACCEPT_LANGUAGE);
// handle no locale
if (acceptable.isEmpty())
return Collections.enumeration(__defaultLocale);
List<Locale> locales = acceptable.stream().map(language ->
{
language = HttpFields.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);
}
/*
* @see javax.servlet.ServletRequest#getLocalAddr()
*/
@Override
public String getLocalAddr()
{
if (_channel == null)
{
try
{
String name = InetAddress.getLocalHost().getHostAddress();
if (StringUtil.ALL_INTERFACES.equals(name))
return null;
return HostPort.normalizeHost(name);