/
Http11OutputBuffer.java
562 lines (447 loc) · 16.3 KB
/
Http11OutputBuffer.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
/*
* 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.nio.ByteBuffer;
import java.util.Arrays;
import org.apache.coyote.ActionCode;
import org.apache.coyote.CloseNowException;
import org.apache.coyote.Response;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.net.SocketWrapperBase;
import org.apache.tomcat.util.res.StringManager;
/**
* Provides buffering for the HTTP headers (allowing responses to be reset before they have been committed) and the link
* to the Socket for writing the headers (once committed) and the response body. Note that buffering of the response
* body happens at a higher level.
*/
public class Http11OutputBuffer implements HttpOutputBuffer {
// -------------------------------------------------------------- Variables
/**
* The string manager for this package.
*/
protected static final StringManager sm = StringManager.getManager(Http11OutputBuffer.class);
// ----------------------------------------------------- Instance Variables
/**
* Associated Coyote response.
*/
protected final Response response;
private volatile boolean ackSent = false;
/**
* Finished flag.
*/
protected boolean responseFinished;
/**
* The buffer used for header composition.
*/
protected final ByteBuffer headerBuffer;
/**
* Filter library for processing the response body.
*/
protected OutputFilter[] filterLibrary;
/**
* Active filters for the current request.
*/
protected OutputFilter[] activeFilters;
/**
* Index of the last active filter.
*/
protected int lastActiveFilter;
/**
* Underlying output buffer.
*/
protected HttpOutputBuffer outputStreamOutputBuffer;
/**
* Wrapper for socket where data will be written to.
*/
protected SocketWrapperBase<?> socketWrapper;
/**
* Bytes written to client for the current request
*/
protected long byteCount = 0;
protected Http11OutputBuffer(Response response, int headerBufferSize) {
this.response = response;
headerBuffer = ByteBuffer.allocate(headerBufferSize);
filterLibrary = new OutputFilter[0];
activeFilters = new OutputFilter[0];
lastActiveFilter = -1;
responseFinished = false;
outputStreamOutputBuffer = new SocketOutputBuffer();
}
// ------------------------------------------------------------- Properties
/**
* Add an output filter to the filter library. Note that calling this method resets the currently active filters to
* none.
*
* @param filter The filter to add
*/
public void addFilter(OutputFilter filter) {
OutputFilter[] newFilterLibrary = Arrays.copyOf(filterLibrary, filterLibrary.length + 1);
newFilterLibrary[filterLibrary.length] = filter;
filterLibrary = newFilterLibrary;
activeFilters = new OutputFilter[filterLibrary.length];
}
/**
* Get filters.
*
* @return The current filter library containing all possible filters
*/
public OutputFilter[] getFilters() {
return filterLibrary;
}
/**
* Add an output filter to the active filters for the current response.
* <p>
* The filter does not have to be present in {@link #getFilters()}.
* <p>
* A filter can only be added to a response once. If the filter has already been added to this response then this
* method will be a NO-OP.
*
* @param filter The filter to add
*/
public void addActiveFilter(OutputFilter filter) {
if (lastActiveFilter == -1) {
filter.setBuffer(outputStreamOutputBuffer);
} else {
for (int i = 0; i <= lastActiveFilter; i++) {
if (activeFilters[i] == filter) {
return;
}
}
filter.setBuffer(activeFilters[lastActiveFilter]);
}
activeFilters[++lastActiveFilter] = filter;
filter.setResponse(response);
}
// --------------------------------------------------- OutputBuffer Methods
@Override
public int doWrite(ByteBuffer chunk) throws IOException {
if (!response.isCommitted()) {
// Send the connector a request for commit. The connector should
// then validate the headers, send them (using sendHeaders) and
// set the filters accordingly.
response.action(ActionCode.COMMIT, null);
}
if (lastActiveFilter == -1) {
return outputStreamOutputBuffer.doWrite(chunk);
} else {
return activeFilters[lastActiveFilter].doWrite(chunk);
}
}
@Override
public long getBytesWritten() {
if (lastActiveFilter == -1) {
return outputStreamOutputBuffer.getBytesWritten();
} else {
return activeFilters[lastActiveFilter].getBytesWritten();
}
}
// ----------------------------------------------- HttpOutputBuffer Methods
@Override
public void flush() throws IOException {
if (lastActiveFilter == -1) {
outputStreamOutputBuffer.flush();
} else {
activeFilters[lastActiveFilter].flush();
}
}
@Override
public void end() throws IOException {
if (responseFinished) {
return;
}
if (lastActiveFilter == -1) {
outputStreamOutputBuffer.end();
} else {
activeFilters[lastActiveFilter].end();
}
responseFinished = true;
}
// --------------------------------------------------------- Public Methods
/**
* Reset the header buffer if an error occurs during the writing of the headers so the error response can be
* written.
*/
void resetHeaderBuffer() {
headerBuffer.position(0).limit(headerBuffer.capacity());
}
/**
* Recycle the output buffer. This should be called when closing the connection.
*/
public void recycle() {
nextRequest();
socketWrapper = null;
}
/**
* End processing of current HTTP request. Note: All bytes of the current request should have been already consumed.
* This method only resets all the pointers so that we are ready to parse the next HTTP request.
*/
public void nextRequest() {
// Recycle filters
for (int i = 0; i <= lastActiveFilter; i++) {
activeFilters[i].recycle();
}
// Recycle response object
response.recycle();
// Reset pointers
headerBuffer.position(0).limit(headerBuffer.capacity());
lastActiveFilter = -1;
ackSent = false;
responseFinished = false;
byteCount = 0;
}
public void init(SocketWrapperBase<?> socketWrapper) {
this.socketWrapper = socketWrapper;
}
public void sendAck() throws IOException {
// It possible that the protocol configuration is changed between the
// request being received and the first read of the body. That could led
// to multiple calls to this method so ensure the ACK is only sent once.
if (!response.isCommitted() && !ackSent) {
ackSent = true;
socketWrapper.write(isBlocking(), Constants.ACK_BYTES, 0, Constants.ACK_BYTES.length);
if (flushBuffer(true)) {
throw new IOException(sm.getString("iob.failedwrite.ack"));
}
}
}
/**
* Commit the response.
*
* @throws IOException an underlying I/O error occurred
*/
protected void commit() throws IOException {
response.setCommitted(true);
if (headerBuffer.position() > 0) {
// Sending the response header buffer
headerBuffer.flip();
try {
SocketWrapperBase<?> socketWrapper = this.socketWrapper;
if (socketWrapper != null) {
socketWrapper.write(isBlocking(), headerBuffer);
} else {
throw new CloseNowException(sm.getString("iob.failedwrite"));
}
} finally {
headerBuffer.position(0).limit(headerBuffer.capacity());
}
}
}
/**
* Send the response status line.
*/
public void sendStatus() {
// Write protocol name
write(Constants.HTTP_11_BYTES);
headerBuffer.put(Constants.SP);
// Write status code
int status = response.getStatus();
switch (status) {
case 200:
write(Constants._200_BYTES);
break;
case 400:
write(Constants._400_BYTES);
break;
case 404:
write(Constants._404_BYTES);
break;
default:
write(status);
}
headerBuffer.put(Constants.SP);
// The reason phrase is optional but the space before it is not. Skip
// sending the reason phrase. Clients should ignore it (RFC 7230) and it
// just wastes bytes.
headerBuffer.put(Constants.CR).put(Constants.LF);
}
/**
* Send a header.
*
* @param name Header name
* @param value Header value
*/
public void sendHeader(MessageBytes name, MessageBytes value) {
write(name);
headerBuffer.put(Constants.COLON).put(Constants.SP);
write(value);
headerBuffer.put(Constants.CR).put(Constants.LF);
}
/**
* End the header block.
*/
public void endHeaders() {
headerBuffer.put(Constants.CR).put(Constants.LF);
}
/**
* This method will write the contents of the specified message bytes buffer to the output stream, without
* filtering. This method is meant to be used to write the response header.
*
* @param mb data to be written
*/
private void write(MessageBytes mb) {
if (mb.getType() != MessageBytes.T_BYTES) {
mb.toBytes();
ByteChunk bc = mb.getByteChunk();
// Need to filter out CTLs excluding TAB. ISO-8859-1 and UTF-8
// values will be OK. Strings using other encodings may be
// corrupted.
byte[] buffer = bc.getBuffer();
for (int i = bc.getStart(); i < bc.getLength(); i++) {
// byte values are signed i.e. -128 to 127
// The values are used unsigned. 0 to 31 are CTLs so they are
// filtered (apart from TAB which is 9). 127 is a control (DEL).
// The values 128 to 255 are all OK. Converting those to signed
// gives -128 to -1.
if ((buffer[i] > -1 && buffer[i] <= 31 && buffer[i] != 9) || buffer[i] == 127) {
buffer[i] = ' ';
}
}
}
write(mb.getByteChunk());
}
/**
* This method will write the contents of the specified byte chunk to the output stream, without filtering. This
* method is meant to be used to write the response header.
*
* @param bc data to be written
*/
private void write(ByteChunk bc) {
// Writing the byte chunk to the output buffer
int length = bc.getLength();
checkLengthBeforeWrite(length);
headerBuffer.put(bc.getBytes(), bc.getStart(), length);
}
/**
* This method will write the contents of the specified byte buffer to the output stream, without filtering. This
* method is meant to be used to write the response header.
*
* @param b data to be written
*/
public void write(byte[] b) {
checkLengthBeforeWrite(b.length);
// Writing the byte chunk to the output buffer
headerBuffer.put(b);
}
/**
* This method will write the specified integer to the output stream. This method is meant to be used to write the
* response header.
*
* @param value data to be written
*/
private void write(int value) {
// From the Tomcat 3.3 HTTP/1.0 connector
String s = Integer.toString(value);
int len = s.length();
checkLengthBeforeWrite(len);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
headerBuffer.put((byte) c);
}
}
/**
* Checks to see if there is enough space in the buffer to write the requested number of bytes.
*/
private void checkLengthBeforeWrite(int length) {
// "+ 4": BZ 57509. Reserve space for CR/LF/COLON/SP characters that
// are put directly into the buffer following this write operation.
if (headerBuffer.position() + length + 4 > headerBuffer.capacity()) {
throw new HeadersTooLargeException(sm.getString("iob.responseheadertoolarge.error"));
}
}
// ------------------------------------------------------ Non-blocking writes
/**
* Writes any remaining buffered data.
*
* @param block Should this method block until the buffer is empty
*
* @return <code>true</code> if data remains in the buffer (which can only happen in non-blocking mode) else
* <code>false</code>.
*
* @throws IOException Error writing data
*/
protected boolean flushBuffer(boolean block) throws IOException {
return socketWrapper.flush(block);
}
/**
* Is standard Servlet blocking IO being used for output?
*
* @return <code>true</code> if this is blocking IO
*/
protected final boolean isBlocking() {
return response.getWriteListener() == null;
}
protected final boolean isReady() {
boolean result = !hasDataToWrite();
if (!result) {
socketWrapper.registerWriteInterest();
}
return result;
}
public boolean hasDataToWrite() {
return socketWrapper.hasDataToWrite();
}
public void registerWriteInterest() {
socketWrapper.registerWriteInterest();
}
boolean isChunking() {
for (int i = 0; i < lastActiveFilter; i++) {
if (activeFilters[i] == filterLibrary[Constants.CHUNKED_FILTER]) {
return true;
}
}
return false;
}
// ------------------------------------------ SocketOutputBuffer Inner Class
/**
* This class is an output buffer which will write data to a socket.
*/
protected class SocketOutputBuffer implements HttpOutputBuffer {
@Override
public int doWrite(ByteBuffer chunk) throws IOException {
try {
int len = chunk.remaining();
SocketWrapperBase<?> socketWrapper = Http11OutputBuffer.this.socketWrapper;
if (socketWrapper != null) {
socketWrapper.write(isBlocking(), chunk);
} else {
throw new CloseNowException(sm.getString("iob.failedwrite"));
}
len -= chunk.remaining();
byteCount += len;
return len;
} catch (IOException ioe) {
response.action(ActionCode.CLOSE_NOW, ioe);
// Re-throw
throw ioe;
}
}
@Override
public long getBytesWritten() {
return byteCount;
}
@Override
public void end() throws IOException {
socketWrapper.flush(response.getWriteListener() == null);
}
@Override
public void flush() throws IOException {
socketWrapper.flush(isBlocking());
}
}
}