-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
AbstractHttp11Processor.java
1774 lines (1531 loc) · 58.5 KB
/
AbstractHttp11Processor.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
/*
* 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.coyote.http11;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.nio.ByteBuffer;
import java.util.Locale;
import java.util.StringTokenizer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Pattern;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpUpgradeHandler;
import org.apache.coyote.AbstractProcessor;
import org.apache.coyote.ActionCode;
import org.apache.coyote.AsyncContextCallback;
import org.apache.coyote.ErrorState;
import org.apache.coyote.RequestInfo;
import org.apache.coyote.http11.filters.BufferedInputFilter;
import org.apache.coyote.http11.filters.ChunkedInputFilter;
import org.apache.coyote.http11.filters.ChunkedOutputFilter;
import org.apache.coyote.http11.filters.GzipOutputFilter;
import org.apache.coyote.http11.filters.IdentityInputFilter;
import org.apache.coyote.http11.filters.IdentityOutputFilter;
import org.apache.coyote.http11.filters.SavedRequestInputFilter;
import org.apache.coyote.http11.filters.VoidInputFilter;
import org.apache.coyote.http11.filters.VoidOutputFilter;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.buf.Ascii;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.HexUtils;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.http.FastHttpDateFormat;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.log.UserDataHelper;
import org.apache.tomcat.util.net.AbstractEndpoint;
import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
import org.apache.tomcat.util.net.DispatchType;
import org.apache.tomcat.util.net.SocketStatus;
import org.apache.tomcat.util.net.SocketWrapperBase;
import org.apache.tomcat.util.res.StringManager;
public abstract class AbstractHttp11Processor<S> extends AbstractProcessor<S> {
private final UserDataHelper userDataHelper;
/**
* The string manager for this package.
*/
protected static final StringManager sm =
StringManager.getManager(Constants.Package);
/**
* Input.
*/
protected AbstractInputBuffer<S> inputBuffer;
/**
* Output.
*/
protected Http11OutputBuffer<S> outputBuffer;
/**
* Tracks how many internal filters are in the filter library so they
* are skipped when looking for pluggable filters.
*/
private int pluggableFilterIndex = Integer.MAX_VALUE;
/**
* Keep-alive.
*/
protected boolean keepAlive = true;
/**
* Flag used to indicate that the socket should be kept open (e.g. for keep
* alive or send file.
*/
protected boolean openSocket = false;
/**
* Flag used to indicate that the socket should treat the next request
* processed like a keep-alive connection - i.e. one where there may not be
* any data to process. The initial value of this flag on entering the
* process method is different for connectors that use polling (NIO / APR -
* data is always expected) compared to those that use blocking (BIO - data
* is only expected if the connection isn't in the keep-alive state).
*/
protected boolean keptAlive;
/**
* Flag that indicates that send file processing is in progress and that the
* socket should not be returned to the poller (where a poller is used).
*/
protected boolean sendfileInProgress = false;
/**
* Flag that indicates if the request headers have been completely read.
*/
protected boolean readComplete = true;
/**
* HTTP/1.1 flag.
*/
protected boolean http11 = true;
/**
* HTTP/0.9 flag.
*/
protected boolean http09 = false;
/**
* Content delimiter for the request (if false, the connection will
* be closed at the end of the request).
*/
protected boolean contentDelimitation = true;
/**
* Is there an expectation ?
*/
protected boolean expectation = false;
/**
* Regular expression that defines the restricted user agents.
*/
protected Pattern restrictedUserAgents = null;
/**
* Maximum number of Keep-Alive requests to honor.
*/
protected int maxKeepAliveRequests = -1;
/**
* The number of seconds Tomcat will wait for a subsequent request
* before closing the connection.
*/
protected int keepAliveTimeout = -1;
/**
* Maximum timeout on uploads. 5 minutes as in Apache HTTPD server.
*/
protected int connectionUploadTimeout = 300000;
/**
* Flag to disable setting a different time-out on uploads.
*/
protected boolean disableUploadTimeout = false;
/**
* Allowed compression level.
*/
protected int compressionLevel = 0;
/**
* Minimum content size to make compression.
*/
protected int compressionMinSize = 2048;
/**
* Max saved post size.
*/
protected int maxSavePostSize = 4 * 1024;
/**
* Regular expression that defines the user agents to not use gzip with
*/
protected Pattern noCompressionUserAgents = null;
/**
* List of MIMES which could be gzipped
*/
protected String[] compressableMimeTypes =
{ "text/html", "text/xml", "text/plain" };
/**
* Host name (used to avoid useless B2C conversion on the host name).
*/
protected char[] hostNameC = new char[0];
/**
* Allow a customized the server header for the tin-foil hat folks.
*/
protected String server = null;
/**
* Instance of the new protocol to use after the HTTP connection has been
* upgraded.
*/
protected HttpUpgradeHandler httpUpgradeHandler = null;
public AbstractHttp11Processor(AbstractEndpoint<S> endpoint) {
super(endpoint);
userDataHelper = new UserDataHelper(getLog());
}
/**
* Set compression level.
*/
public void setCompression(String compression) {
if (compression.equals("on")) {
this.compressionLevel = 1;
} else if (compression.equals("force")) {
this.compressionLevel = 2;
} else if (compression.equals("off")) {
this.compressionLevel = 0;
} else {
try {
// Try to parse compression as an int, which would give the
// minimum compression size
compressionMinSize = Integer.parseInt(compression);
this.compressionLevel = 1;
} catch (Exception e) {
this.compressionLevel = 0;
}
}
}
/**
* Set Minimum size to trigger compression.
*/
public void setCompressionMinSize(int compressionMinSize) {
this.compressionMinSize = compressionMinSize;
}
/**
* Set no compression user agent pattern. Regular expression as supported
* by {@link Pattern}.
*
* ie: "gorilla|desesplorer|tigrus"
*/
public void setNoCompressionUserAgents(String noCompressionUserAgents) {
if (noCompressionUserAgents == null || noCompressionUserAgents.length() == 0) {
this.noCompressionUserAgents = null;
} else {
this.noCompressionUserAgents =
Pattern.compile(noCompressionUserAgents);
}
}
/**
* Add a mime-type which will be compressible
* The mime-type String will be exactly matched
* in the response mime-type header .
*
* @param mimeType mime-type string
*/
public void addCompressableMimeType(String mimeType) {
compressableMimeTypes =
addStringArray(compressableMimeTypes, mimeType);
}
/**
* Set compressible mime-type list (this method is best when used with
* a large number of connectors, where it would be better to have all of
* them referenced a single array).
*/
public void setCompressableMimeTypes(String[] compressableMimeTypes) {
this.compressableMimeTypes = compressableMimeTypes;
}
/**
* Set compressable mime-type list
* List contains users agents separated by ',' :
*
* ie: "text/html,text/xml,text/plain"
*/
public void setCompressableMimeTypes(String compressableMimeTypes) {
if (compressableMimeTypes != null) {
this.compressableMimeTypes = null;
StringTokenizer st = new StringTokenizer(compressableMimeTypes, ",");
while (st.hasMoreTokens()) {
addCompressableMimeType(st.nextToken().trim());
}
}
}
/**
* Return compression level.
*/
public String getCompression() {
switch (compressionLevel) {
case 0:
return "off";
case 1:
return "on";
case 2:
return "force";
}
return "off";
}
/**
* General use method
*
* @param sArray the StringArray
* @param value string
*/
private String[] addStringArray(String sArray[], String value) {
String[] result = null;
if (sArray == null) {
result = new String[1];
result[0] = value;
}
else {
result = new String[sArray.length + 1];
for (int i = 0; i < sArray.length; i++) {
result[i] = sArray[i];
}
result[sArray.length] = value;
}
return result;
}
/**
* Checks if any entry in the string array starts with the specified value
*
* @param sArray the StringArray
* @param value string
*/
private boolean startsWithStringArray(String sArray[], String value) {
if (value == null) {
return false;
}
for (int i = 0; i < sArray.length; i++) {
if (value.startsWith(sArray[i])) {
return true;
}
}
return false;
}
/**
* Set restricted user agent list (which will downgrade the connector
* to HTTP/1.0 mode). Regular expression as supported by {@link Pattern}.
*
* ie: "gorilla|desesplorer|tigrus"
*/
public void setRestrictedUserAgents(String restrictedUserAgents) {
if (restrictedUserAgents == null ||
restrictedUserAgents.length() == 0) {
this.restrictedUserAgents = null;
} else {
this.restrictedUserAgents = Pattern.compile(restrictedUserAgents);
}
}
/**
* Set the maximum number of Keep-Alive requests to honor.
* This is to safeguard from DoS attacks. Setting to a negative
* value disables the check.
*/
public void setMaxKeepAliveRequests(int mkar) {
maxKeepAliveRequests = mkar;
}
/**
* Return the number of Keep-Alive requests that we will honor.
*/
public int getMaxKeepAliveRequests() {
return maxKeepAliveRequests;
}
/**
* Set the Keep-Alive timeout.
*/
public void setKeepAliveTimeout(int timeout) {
keepAliveTimeout = timeout;
}
/**
* Return the number Keep-Alive timeout.
*/
public int getKeepAliveTimeout() {
return keepAliveTimeout;
}
/**
* Set the maximum size of a POST which will be buffered in SSL mode.
*/
public void setMaxSavePostSize(int msps) {
maxSavePostSize = msps;
}
/**
* Return the maximum size of a POST which will be buffered in SSL mode.
*/
public int getMaxSavePostSize() {
return maxSavePostSize;
}
/**
* Set the flag to control upload time-outs.
*/
public void setDisableUploadTimeout(boolean isDisabled) {
disableUploadTimeout = isDisabled;
}
/**
* Get the flag that controls upload time-outs.
*/
public boolean getDisableUploadTimeout() {
return disableUploadTimeout;
}
/**
* Set the upload timeout.
*/
public void setConnectionUploadTimeout(int timeout) {
connectionUploadTimeout = timeout ;
}
/**
* Get the upload timeout.
*/
public int getConnectionUploadTimeout() {
return connectionUploadTimeout;
}
/**
* Set the server header name.
*/
public void setServer( String server ) {
if (server==null || server.equals("")) {
this.server = null;
} else {
this.server = server;
}
}
/**
* Get the server header name.
*/
public String getServer() {
return server;
}
/**
* Check if the resource could be compressed, if the client supports it.
*/
private boolean isCompressable() {
// Check if content is not already gzipped
MessageBytes contentEncodingMB =
response.getMimeHeaders().getValue("Content-Encoding");
if ((contentEncodingMB != null)
&& (contentEncodingMB.indexOf("gzip") != -1)) {
return false;
}
// If force mode, always compress (test purposes only)
if (compressionLevel == 2) {
return true;
}
// Check if sufficient length to trigger the compression
long contentLength = response.getContentLengthLong();
if ((contentLength == -1)
|| (contentLength > compressionMinSize)) {
// Check for compatible MIME-TYPE
if (compressableMimeTypes != null) {
return (startsWithStringArray(compressableMimeTypes,
response.getContentType()));
}
}
return false;
}
/**
* Check if compression should be used for this resource. Already checked
* that the resource could be compressed if the client supports it.
*/
private boolean useCompression() {
// Check if browser support gzip encoding
MessageBytes acceptEncodingMB =
request.getMimeHeaders().getValue("accept-encoding");
if ((acceptEncodingMB == null)
|| (acceptEncodingMB.indexOf("gzip") == -1)) {
return false;
}
// If force mode, always compress (test purposes only)
if (compressionLevel == 2) {
return true;
}
// Check for incompatible Browser
if (noCompressionUserAgents != null) {
MessageBytes userAgentValueMB =
request.getMimeHeaders().getValue("user-agent");
if(userAgentValueMB != null) {
String userAgentValue = userAgentValueMB.toString();
if (noCompressionUserAgents != null &&
noCompressionUserAgents.matcher(userAgentValue).matches()) {
return false;
}
}
}
return true;
}
/**
* Specialized utility method: find a sequence of lower case bytes inside
* a ByteChunk.
*/
protected int findBytes(ByteChunk bc, byte[] b) {
byte first = b[0];
byte[] buff = bc.getBuffer();
int start = bc.getStart();
int end = bc.getEnd();
// Look for first char
int srcEnd = b.length;
for (int i = start; i <= (end - srcEnd); i++) {
if (Ascii.toLower(buff[i]) != first) {
continue;
}
// found first char, now look for a match
int myPos = i+1;
for (int srcPos = 1; srcPos < srcEnd;) {
if (Ascii.toLower(buff[myPos++]) != b[srcPos++]) {
break;
}
if (srcPos == srcEnd) {
return i - start; // found it
}
}
}
return -1;
}
/**
* Determine if we must drop the connection because of the HTTP status
* code. Use the same list of codes as Apache/httpd.
*/
protected boolean statusDropsConnection(int status) {
return status == 400 /* SC_BAD_REQUEST */ ||
status == 408 /* SC_REQUEST_TIMEOUT */ ||
status == 411 /* SC_LENGTH_REQUIRED */ ||
status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ ||
status == 414 /* SC_REQUEST_URI_TOO_LONG */ ||
status == 500 /* SC_INTERNAL_SERVER_ERROR */ ||
status == 503 /* SC_SERVICE_UNAVAILABLE */ ||
status == 501 /* SC_NOT_IMPLEMENTED */;
}
/**
* Exposes input buffer to super class to allow better code re-use.
* @return The input buffer used by the processor.
*/
protected AbstractInputBuffer<S> getInputBuffer() {
return inputBuffer;
}
/**
* Exposes output buffer to super class to allow better code re-use.
* @return The output buffer used by the processor.
*/
protected Http11OutputBuffer<S> getOutputBuffer() {
return outputBuffer;
}
/**
* Initialize standard input and output filters.
*/
protected void initializeFilters(int maxTrailerSize, int maxExtensionSize,
int maxSwallowSize) {
// Create and add the identity filters.
getInputBuffer().addFilter(new IdentityInputFilter(maxSwallowSize));
getOutputBuffer().addFilter(new IdentityOutputFilter());
// Create and add the chunked filters.
getInputBuffer().addFilter(
new ChunkedInputFilter(maxTrailerSize, maxExtensionSize, maxSwallowSize));
getOutputBuffer().addFilter(new ChunkedOutputFilter());
// Create and add the void filters.
getInputBuffer().addFilter(new VoidInputFilter());
getOutputBuffer().addFilter(new VoidOutputFilter());
// Create and add buffered input filter
getInputBuffer().addFilter(new BufferedInputFilter());
// Create and add the chunked filters.
//getInputBuffer().addFilter(new GzipInputFilter());
getOutputBuffer().addFilter(new GzipOutputFilter());
pluggableFilterIndex = getInputBuffer().getFilters().length;
}
/**
* Add an input filter to the current request. If the encoding is not
* supported, a 501 response will be returned to the client.
*/
private void addInputFilter(InputFilter[] inputFilters, String encodingName) {
// Trim provided encoding name and convert to lower case since transfer
// encoding names are case insensitive. (RFC2616, section 3.6)
encodingName = encodingName.trim().toLowerCase(Locale.ENGLISH);
if (encodingName.equals("identity")) {
// Skip
} else if (encodingName.equals("chunked")) {
getInputBuffer().addActiveFilter
(inputFilters[Constants.CHUNKED_FILTER]);
contentDelimitation = true;
} else {
for (int i = pluggableFilterIndex; i < inputFilters.length; i++) {
if (inputFilters[i].getEncodingName().toString().equals(encodingName)) {
getInputBuffer().addActiveFilter(inputFilters[i]);
return;
}
}
// Unsupported transfer encoding
// 501 - Unimplemented
response.setStatus(501);
setErrorState(ErrorState.CLOSE_CLEAN, null);
if (getLog().isDebugEnabled()) {
getLog().debug(sm.getString("http11processor.request.prepare") +
" Unsupported transfer encoding [" + encodingName + "]");
}
}
}
/**
* Send an action to the connector.
*
* @param actionCode Type of the action
* @param param Action parameter
*/
@Override
public final void action(ActionCode actionCode, Object param) {
switch (actionCode) {
case CLOSE: {
// End the processing of the current request
try {
getOutputBuffer().endRequest();
} catch (IOException e) {
setErrorState(ErrorState.CLOSE_NOW, e);
}
break;
}
case COMMIT: {
// Commit current response
if (response.isCommitted()) {
return;
}
// Validate and write response headers
try {
prepareResponse();
getOutputBuffer().commit();
} catch (IOException e) {
setErrorState(ErrorState.CLOSE_NOW, e);
}
break;
}
case ACK: {
// Acknowledge request
// Send a 100 status back if it makes sense (response not committed
// yet, and client specified an expectation for 100-continue)
if ((response.isCommitted()) || !expectation) {
return;
}
getInputBuffer().setSwallowInput(true);
try {
getOutputBuffer().sendAck();
} catch (IOException e) {
setErrorState(ErrorState.CLOSE_NOW, e);
}
break;
}
case CLIENT_FLUSH: {
try {
getOutputBuffer().flush();
} catch (IOException e) {
setErrorState(ErrorState.CLOSE_NOW, e);
response.setErrorException(e);
}
break;
}
case IS_ERROR: {
((AtomicBoolean) param).set(getErrorState().isError());
break;
}
case DISABLE_SWALLOW_INPUT: {
// Do not swallow request input and make sure we are closing the
// connection
setErrorState(ErrorState.CLOSE_CLEAN, null);
getInputBuffer().setSwallowInput(false);
break;
}
case RESET: {
// Note: This must be called before the response is committed
getOutputBuffer().reset();
break;
}
case REQ_SET_BODY_REPLAY: {
ByteChunk body = (ByteChunk) param;
InputFilter savedBody = new SavedRequestInputFilter(body);
savedBody.setRequest(request);
@SuppressWarnings("unchecked")
AbstractInputBuffer<S> internalBuffer = (AbstractInputBuffer<S>)
request.getInputBuffer();
internalBuffer.addActiveFilter(savedBody);
break;
}
case ASYNC_START: {
asyncStateMachine.asyncStart((AsyncContextCallback) param);
break;
}
case ASYNC_DISPATCHED: {
asyncStateMachine.asyncDispatched();
break;
}
case ASYNC_TIMEOUT: {
AtomicBoolean result = (AtomicBoolean) param;
result.set(asyncStateMachine.asyncTimeout());
break;
}
case ASYNC_RUN: {
asyncStateMachine.asyncRun((Runnable) param);
break;
}
case ASYNC_ERROR: {
asyncStateMachine.asyncError();
break;
}
case ASYNC_IS_STARTED: {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted());
break;
}
case ASYNC_IS_COMPLETING: {
((AtomicBoolean) param).set(asyncStateMachine.isCompleting());
break;
}
case ASYNC_IS_DISPATCHING: {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching());
break;
}
case ASYNC_IS_ASYNC: {
((AtomicBoolean) param).set(asyncStateMachine.isAsync());
break;
}
case ASYNC_IS_TIMINGOUT: {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut());
break;
}
case ASYNC_IS_ERROR: {
((AtomicBoolean) param).set(asyncStateMachine.isAsyncError());
break;
}
case ASYNC_COMPLETE: {
socketWrapper.clearDispatches();
if (asyncStateMachine.asyncComplete()) {
endpoint.processSocket(this.socketWrapper, SocketStatus.OPEN_READ, true);
}
break;
}
case ASYNC_SETTIMEOUT: {
if (param == null || socketWrapper == null) {
return;
}
long timeout = ((Long) param).longValue();
socketWrapper.setAsyncTimeout(timeout);
break;
}
case ASYNC_DISPATCH: {
if (asyncStateMachine.asyncDispatch()) {
endpoint.processSocket(this.socketWrapper, SocketStatus.OPEN_READ, true);
}
break;
}
case UPGRADE: {
httpUpgradeHandler = (HttpUpgradeHandler) param;
// Stop further HTTP output
getOutputBuffer().finished = true;
break;
}
case AVAILABLE: {
request.setAvailable(getInputBuffer().available());
break;
}
case NB_WRITE_INTEREST: {
AtomicBoolean isReady = (AtomicBoolean)param;
isReady.set(getOutputBuffer().isReady());
break;
}
case NB_READ_INTEREST: {
registerForEvent(true, false);
break;
}
case REQUEST_BODY_FULLY_READ: {
AtomicBoolean result = (AtomicBoolean) param;
result.set(getInputBuffer().isFinished());
break;
}
case DISPATCH_READ: {
socketWrapper.addDispatch(DispatchType.NON_BLOCKING_READ);
break;
}
case DISPATCH_WRITE: {
socketWrapper.addDispatch(DispatchType.NON_BLOCKING_WRITE);
break;
}
case DISPATCH_EXECUTE: {
SocketWrapperBase<S> wrapper = socketWrapper;
if (wrapper != null) {
getEndpoint().executeNonBlockingDispatches(wrapper);
}
break;
}
case CLOSE_NOW: {
// Block further output
getOutputBuffer().finished = true;
setErrorState(ErrorState.CLOSE_NOW, null);
break;
}
default: {
actionInternal(actionCode, param);
break;
}
}
}
abstract void actionInternal(ActionCode actionCode, Object param);
/**
* Defines how a connector handles an incomplete request line read.
*
* @return <code>true</code> if the processor should break out of the
* processing loop, otherwise <code>false</code>.
*/
protected abstract boolean handleIncompleteRequestLineRead();
/**
* Set the socket timeout.
*/
protected abstract void setSocketTimeout(int timeout) throws IOException;
/**
* Process pipelined HTTP requests using the specified input and output
* streams.
*
* @param socketWrapper Socket from which the HTTP requests will be read
* and the HTTP responses will be written.
*
* @throws IOException error during an I/O operation
*/
@Override
public SocketState process(SocketWrapperBase<S> socketWrapper)
throws IOException {
RequestInfo rp = request.getRequestProcessor();
rp.setStage(org.apache.coyote.Constants.STAGE_PARSE);
// Setting up the I/O
setSocketWrapper(socketWrapper);
getInputBuffer().init(socketWrapper, endpoint);
getOutputBuffer().init(socketWrapper);
// Flags
keepAlive = true;
openSocket = false;
sendfileInProgress = false;
readComplete = true;
keptAlive = false;
while (!getErrorState().isError() && keepAlive && !isAsync() &&
httpUpgradeHandler == null && !endpoint.isPaused()) {
// Parsing the request header
try {
if (!getInputBuffer().parseRequestLine(keptAlive)) {
if (handleIncompleteRequestLineRead()) {
break;
}
}
if (endpoint.isPaused()) {
// 503 - Service unavailable
response.setStatus(503);
setErrorState(ErrorState.CLOSE_CLEAN, null);
} else {
keptAlive = true;
// Set this every time in case limit has been changed via JMX
request.getMimeHeaders().setLimit(endpoint.getMaxHeaderCount());
// Currently only NIO will ever return false here
if (!getInputBuffer().parseHeaders()) {
// We've read part of the request, don't recycle it
// instead associate it with the socket
openSocket = true;
readComplete = false;
break;
}
if (!disableUploadTimeout) {
setSocketTimeout(connectionUploadTimeout);
}
}
} catch (IOException e) {
if (getLog().isDebugEnabled()) {
getLog().debug(
sm.getString("http11processor.header.parse"), e);
}
setErrorState(ErrorState.CLOSE_NOW, e);
break;
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
UserDataHelper.Mode logMode = userDataHelper.getNextMode();
if (logMode != null) {
String message = sm.getString(
"http11processor.header.parse");
switch (logMode) {
case INFO_THEN_DEBUG:
message += sm.getString(
"http11processor.fallToDebug");
//$FALL-THROUGH$
case INFO:
getLog().info(message);
break;
case DEBUG:
getLog().debug(message);
}