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 package org.apache.hc.core5.http.impl.nio;
29
30 import java.io.IOException;
31 import java.net.SocketAddress;
32 import java.nio.ByteBuffer;
33 import java.nio.channels.ClosedChannelException;
34 import java.nio.channels.ReadableByteChannel;
35 import java.nio.channels.SelectionKey;
36 import java.nio.channels.WritableByteChannel;
37 import java.util.List;
38 import java.util.concurrent.atomic.AtomicInteger;
39
40 import javax.net.ssl.SSLSession;
41
42 import org.apache.hc.core5.http.ConnectionClosedException;
43 import org.apache.hc.core5.http.ContentLengthStrategy;
44 import org.apache.hc.core5.http.EndpointDetails;
45 import org.apache.hc.core5.http.EntityDetails;
46 import org.apache.hc.core5.http.Header;
47 import org.apache.hc.core5.http.HttpConnection;
48 import org.apache.hc.core5.http.HttpException;
49 import org.apache.hc.core5.http.HttpMessage;
50 import org.apache.hc.core5.http.Message;
51 import org.apache.hc.core5.http.ProtocolVersion;
52 import org.apache.hc.core5.http.config.CharCodingConfig;
53 import org.apache.hc.core5.http.config.Http1Config;
54 import org.apache.hc.core5.http.impl.BasicEndpointDetails;
55 import org.apache.hc.core5.http.impl.BasicHttpConnectionMetrics;
56 import org.apache.hc.core5.http.impl.BasicHttpTransportMetrics;
57 import org.apache.hc.core5.http.impl.CharCodingSupport;
58 import org.apache.hc.core5.http.impl.DefaultContentLengthStrategy;
59 import org.apache.hc.core5.http.impl.IncomingEntityDetails;
60 import org.apache.hc.core5.http.nio.CapacityChannel;
61 import org.apache.hc.core5.http.nio.ContentDecoder;
62 import org.apache.hc.core5.http.nio.ContentEncoder;
63 import org.apache.hc.core5.http.nio.NHttpMessageParser;
64 import org.apache.hc.core5.http.nio.NHttpMessageWriter;
65 import org.apache.hc.core5.http.nio.SessionInputBuffer;
66 import org.apache.hc.core5.http.nio.SessionOutputBuffer;
67 import org.apache.hc.core5.http.nio.command.CommandSupport;
68 import org.apache.hc.core5.http.nio.command.RequestExecutionCommand;
69 import org.apache.hc.core5.http.nio.command.ShutdownCommand;
70 import org.apache.hc.core5.io.CloseMode;
71 import org.apache.hc.core5.io.SocketTimeoutExceptionFactory;
72 import org.apache.hc.core5.reactor.Command;
73 import org.apache.hc.core5.reactor.EventMask;
74 import org.apache.hc.core5.reactor.IOSession;
75 import org.apache.hc.core5.reactor.ProtocolIOSession;
76 import org.apache.hc.core5.reactor.ssl.TlsDetails;
77 import org.apache.hc.core5.util.Args;
78 import org.apache.hc.core5.util.Identifiable;
79 import org.apache.hc.core5.util.Timeout;
80
81 abstract class AbstractHttp1StreamDuplexer<IncomingMessage extends HttpMessage, OutgoingMessage extends HttpMessage>
82 implements Identifiable, HttpConnection {
83
84 private enum ConnectionState { READY, ACTIVE, GRACEFUL_SHUTDOWN, SHUTDOWN}
85
86 private final ProtocolIOSession ioSession;
87 private final Http1Config http1Config;
88 private final SessionInputBufferImpl inbuf;
89 private final SessionOutputBufferImpl outbuf;
90 private final BasicHttpTransportMetrics inTransportMetrics;
91 private final BasicHttpTransportMetrics outTransportMetrics;
92 private final BasicHttpConnectionMetrics connMetrics;
93 private final NHttpMessageParser<IncomingMessage> incomingMessageParser;
94 private final NHttpMessageWriter<OutgoingMessage> outgoingMessageWriter;
95 private final ContentLengthStrategy incomingContentStrategy;
96 private final ContentLengthStrategy outgoingContentStrategy;
97 private final ByteBuffer contentBuffer;
98 private final AtomicInteger outputRequests;
99
100 private volatile Message<IncomingMessage, ContentDecoder> incomingMessage;
101 private volatile Message<OutgoingMessage, ContentEncoder> outgoingMessage;
102 private volatile ConnectionState connState;
103 private volatile CapacityWindow capacityWindow;
104
105 private volatile ProtocolVersion version;
106 private volatile EndpointDetails endpointDetails;
107
108 AbstractHttp1StreamDuplexer(
109 final ProtocolIOSession ioSession,
110 final Http1Config http1Config,
111 final CharCodingConfig charCodingConfig,
112 final NHttpMessageParser<IncomingMessage> incomingMessageParser,
113 final NHttpMessageWriter<OutgoingMessage> outgoingMessageWriter,
114 final ContentLengthStrategy incomingContentStrategy,
115 final ContentLengthStrategy outgoingContentStrategy) {
116 this.ioSession = Args.notNull(ioSession, "I/O session");
117 this.http1Config = http1Config != null ? http1Config : Http1Config.DEFAULT;
118 final int bufferSize = this.http1Config.getBufferSize();
119 this.inbuf = new SessionInputBufferImpl(bufferSize, bufferSize < 512 ? bufferSize : 512,
120 this.http1Config.getMaxLineLength(),
121 CharCodingSupport.createDecoder(charCodingConfig));
122 this.outbuf = new SessionOutputBufferImpl(bufferSize, bufferSize < 512 ? bufferSize : 512,
123 CharCodingSupport.createEncoder(charCodingConfig));
124 this.inTransportMetrics = new BasicHttpTransportMetrics();
125 this.outTransportMetrics = new BasicHttpTransportMetrics();
126 this.connMetrics = new BasicHttpConnectionMetrics(inTransportMetrics, outTransportMetrics);
127 this.incomingMessageParser = incomingMessageParser;
128 this.outgoingMessageWriter = outgoingMessageWriter;
129 this.incomingContentStrategy = incomingContentStrategy != null ? incomingContentStrategy :
130 DefaultContentLengthStrategy.INSTANCE;
131 this.outgoingContentStrategy = outgoingContentStrategy != null ? outgoingContentStrategy :
132 DefaultContentLengthStrategy.INSTANCE;
133 this.contentBuffer = ByteBuffer.allocate(this.http1Config.getBufferSize());
134 this.outputRequests = new AtomicInteger(0);
135 this.connState = ConnectionState.READY;
136 }
137
138 @Override
139 public String getId() {
140 return ioSession.getId();
141 }
142
143 boolean isActive() {
144 return connState == ConnectionState.ACTIVE;
145 }
146
147 boolean isShuttingDown() {
148 return connState.compareTo(ConnectionState.GRACEFUL_SHUTDOWN) >= 0;
149 }
150
151 void shutdownSession(final CloseMode closeMode) {
152 if (closeMode == CloseMode.GRACEFUL) {
153 connState = ConnectionState.GRACEFUL_SHUTDOWN;
154 ioSession.enqueue(ShutdownCommand.GRACEFUL, Command.Priority.NORMAL);
155 } else {
156 connState = ConnectionState.SHUTDOWN;
157 ioSession.close();
158 }
159 }
160
161 void shutdownSession(final Exception cause) {
162 connState = ConnectionState.SHUTDOWN;
163 try {
164 terminate(cause);
165 } finally {
166 final CloseMode closeMode;
167 if (cause instanceof ConnectionClosedException) {
168 closeMode = CloseMode.GRACEFUL;
169 } else if (cause instanceof IOException) {
170 closeMode = CloseMode.IMMEDIATE;
171 } else {
172 closeMode = CloseMode.GRACEFUL;
173 }
174 ioSession.close(closeMode);
175 }
176 }
177
178 abstract void disconnected();
179
180 abstract void terminate(final Exception exception);
181
182 abstract void updateInputMetrics(IncomingMessage incomingMessage, BasicHttpConnectionMetrics connMetrics);
183
184 abstract void updateOutputMetrics(OutgoingMessage outgoingMessage, BasicHttpConnectionMetrics connMetrics);
185
186 abstract void consumeHeader(IncomingMessage messageHead, EntityDetails entityDetails) throws HttpException, IOException;
187
188 abstract boolean handleIncomingMessage(IncomingMessage incomingMessage) throws HttpException;
189
190 abstract boolean handleOutgoingMessage(OutgoingMessage outgoingMessage) throws HttpException;
191
192 abstract ContentDecoder createContentDecoder(
193 long contentLength,
194 ReadableByteChannel channel,
195 SessionInputBuffer buffer,
196 BasicHttpTransportMetrics metrics) throws HttpException;
197
198 abstract ContentEncoder createContentEncoder(
199 long contentLength,
200 WritableByteChannel channel,
201 SessionOutputBuffer buffer,
202 BasicHttpTransportMetrics metrics) throws HttpException;
203
204 abstract void consumeData(ByteBuffer src) throws HttpException, IOException;
205
206 abstract void updateCapacity(CapacityChannel capacityChannel) throws HttpException, IOException;
207
208 abstract void dataEnd(List<? extends Header> trailers) throws HttpException, IOException;
209
210 abstract boolean isOutputReady();
211
212 abstract void produceOutput() throws HttpException, IOException;
213
214 abstract void execute(RequestExecutionCommand executionCommand) throws HttpException, IOException;
215
216 abstract void inputEnd() throws HttpException, IOException;
217
218 abstract void outputEnd() throws HttpException, IOException;
219
220 abstract boolean inputIdle();
221
222 abstract boolean outputIdle();
223
224 abstract boolean handleTimeout();
225
226 private void processCommands() throws HttpException, IOException {
227 for (;;) {
228 final Command command = ioSession.poll();
229 if (command == null) {
230 return;
231 }
232 if (command instanceof ShutdownCommand) {
233 final ShutdownCommand../org/apache/hc/core5/http/nio/command/ShutdownCommand.html#ShutdownCommand">ShutdownCommand shutdownCommand = (ShutdownCommand) command;
234 requestShutdown(shutdownCommand.getType());
235 } else if (command instanceof RequestExecutionCommand) {
236 if (connState.compareTo(ConnectionState.GRACEFUL_SHUTDOWN) >= 0) {
237 command.cancel();
238 } else {
239 execute((RequestExecutionCommand) command);
240 return;
241 }
242 } else {
243 throw new HttpException("Unexpected command: " + command.getClass());
244 }
245 }
246 }
247
248 public final void onConnect() throws HttpException, IOException {
249 if (connState == ConnectionState.READY) {
250 connState = ConnectionState.ACTIVE;
251 processCommands();
252 }
253 }
254
255 IncomingMessage parseMessageHead(final boolean endOfStream) throws IOException, HttpException {
256 final IncomingMessage messageHead = incomingMessageParser.parse(inbuf, endOfStream);
257 if (messageHead != null) {
258 incomingMessageParser.reset();
259 }
260 return messageHead;
261 }
262
263 public final void onInput(final ByteBuffer src) throws HttpException, IOException {
264 if (src != null) {
265 inbuf.put(src);
266 }
267
268 if (connState.compareTo(ConnectionState.GRACEFUL_SHUTDOWN) >= 0 && inbuf.hasData() && inputIdle()) {
269 ioSession.clearEvent(SelectionKey.OP_READ);
270 return;
271 }
272
273 boolean endOfStream = false;
274 if (incomingMessage == null) {
275 final int bytesRead = inbuf.fill(ioSession);
276 if (bytesRead > 0) {
277 inTransportMetrics.incrementBytesTransferred(bytesRead);
278 }
279 endOfStream = bytesRead == -1;
280 }
281
282 do {
283 if (incomingMessage == null) {
284
285 final IncomingMessage messageHead = parseMessageHead(endOfStream);
286 if (messageHead != null) {
287 this.version = messageHead.getVersion();
288
289 updateInputMetrics(messageHead, connMetrics);
290 final ContentDecoder contentDecoder;
291 if (handleIncomingMessage(messageHead)) {
292 final long len = incomingContentStrategy.determineLength(messageHead);
293 contentDecoder = createContentDecoder(len, ioSession, inbuf, inTransportMetrics);
294 consumeHeader(messageHead, contentDecoder != null ? new IncomingEntityDetails(messageHead, len) : null);
295 } else {
296 consumeHeader(messageHead, null);
297 contentDecoder = null;
298 }
299 capacityWindow = new CapacityWindow(http1Config.getInitialWindowSize(), ioSession);
300 if (contentDecoder != null) {
301 incomingMessage = new Message<>(messageHead, contentDecoder);
302 } else {
303 inputEnd();
304 if (connState.compareTo(ConnectionState.ACTIVE) == 0) {
305 ioSession.setEvent(SelectionKey.OP_READ);
306 }
307 }
308 } else {
309 break;
310 }
311 }
312
313 if (incomingMessage != null) {
314 final ContentDecoder contentDecoder = incomingMessage.getBody();
315
316
317
318
319
320 final int bytesRead = contentDecoder.read(contentBuffer);
321 if (bytesRead > 0) {
322 contentBuffer.flip();
323 consumeData(contentBuffer);
324 contentBuffer.clear();
325 final int capacity = capacityWindow.removeCapacity(bytesRead);
326 if (capacity <= 0) {
327 if (!contentDecoder.isCompleted()) {
328 updateCapacity(capacityWindow);
329 }
330 }
331 }
332 if (contentDecoder.isCompleted()) {
333 dataEnd(contentDecoder.getTrailers());
334 capacityWindow.close();
335 incomingMessage = null;
336 ioSession.setEvent(SelectionKey.OP_READ);
337 inputEnd();
338 }
339 if (bytesRead == 0) {
340 break;
341 }
342 }
343 } while (inbuf.hasData());
344
345 if (endOfStream && !inbuf.hasData()) {
346 if (outputIdle() && inputIdle()) {
347 requestShutdown(CloseMode.GRACEFUL);
348 } else {
349 shutdownSession(new ConnectionClosedException("Connection closed by peer"));
350 }
351 }
352 }
353
354 public final void onOutput() throws IOException, HttpException {
355 ioSession.getLock().lock();
356 try {
357 if (outbuf.hasData()) {
358 final int bytesWritten = outbuf.flush(ioSession);
359 if (bytesWritten > 0) {
360 outTransportMetrics.incrementBytesTransferred(bytesWritten);
361 }
362 }
363 } finally {
364 ioSession.getLock().unlock();
365 }
366 if (connState.compareTo(ConnectionState.SHUTDOWN) < 0) {
367 final int pendingOutputRequests = outputRequests.get();
368 produceOutput();
369 final boolean outputPending = isOutputReady();
370 final boolean outputEnd;
371 ioSession.getLock().lock();
372 try {
373 if (!outputPending && !outbuf.hasData() && outputRequests.compareAndSet(pendingOutputRequests, 0)) {
374 ioSession.clearEvent(SelectionKey.OP_WRITE);
375 } else {
376 outputRequests.addAndGet(-pendingOutputRequests);
377 }
378 outputEnd = outgoingMessage == null && !outbuf.hasData();
379 } finally {
380 ioSession.getLock().unlock();
381 }
382 if (outputEnd) {
383 outputEnd();
384 if (connState.compareTo(ConnectionState.ACTIVE) == 0) {
385 processCommands();
386 } else if (connState.compareTo(ConnectionState.GRACEFUL_SHUTDOWN) >= 0 && inputIdle() && outputIdle()) {
387 connState = ConnectionState.SHUTDOWN;
388 }
389 }
390 }
391 if (connState.compareTo(ConnectionState.SHUTDOWN) >= 0) {
392 ioSession.close();
393 }
394 }
395
396 public final void onTimeout(final Timeout timeout) throws IOException, HttpException {
397 if (!handleTimeout()) {
398 onException(SocketTimeoutExceptionFactory.create(timeout));
399 }
400 }
401
402 public final void onException(final Exception ex) {
403 shutdownSession(ex);
404 CommandSupport.failCommands(ioSession, ex);
405 }
406
407 public final void onDisconnect() {
408 disconnected();
409 CommandSupport.cancelCommands(ioSession);
410 }
411
412 void requestShutdown(final CloseMode closeMode) {
413 switch (closeMode) {
414 case GRACEFUL:
415 if (connState == ConnectionState.ACTIVE) {
416 connState = ConnectionState.GRACEFUL_SHUTDOWN;
417 }
418 break;
419 case IMMEDIATE:
420 connState = ConnectionState.SHUTDOWN;
421 break;
422 }
423 ioSession.setEvent(SelectionKey.OP_WRITE);
424 }
425
426 void commitMessageHead(
427 final OutgoingMessage messageHead,
428 final boolean endStream,
429 final FlushMode flushMode) throws HttpException, IOException {
430 ioSession.getLock().lock();
431 try {
432 outgoingMessageWriter.write(messageHead, outbuf);
433 updateOutputMetrics(messageHead, connMetrics);
434 if (!endStream) {
435 final ContentEncoder contentEncoder;
436 if (handleOutgoingMessage(messageHead)) {
437 final long len = outgoingContentStrategy.determineLength(messageHead);
438 contentEncoder = createContentEncoder(len, ioSession, outbuf, outTransportMetrics);
439 } else {
440 contentEncoder = null;
441 }
442 if (contentEncoder != null) {
443 outgoingMessage = new Message<>(messageHead, contentEncoder);
444 }
445 }
446 outgoingMessageWriter.reset();
447 if (flushMode == FlushMode.IMMEDIATE) {
448 outbuf.flush(ioSession);
449 }
450 ioSession.setEvent(EventMask.WRITE);
451 } finally {
452 ioSession.getLock().unlock();
453 }
454 }
455
456 void requestSessionInput() {
457 ioSession.setEvent(SelectionKey.OP_READ);
458 }
459
460 void requestSessionOutput() {
461 outputRequests.incrementAndGet();
462 ioSession.setEvent(SelectionKey.OP_WRITE);
463 }
464
465 Timeout getSessionTimeout() {
466 return ioSession.getSocketTimeout();
467 }
468
469 void setSessionTimeout(final Timeout timeout) {
470 ioSession.setSocketTimeout(timeout);
471 }
472
473 void suspendSessionInput() {
474 ioSession.clearEvent(SelectionKey.OP_READ);
475 }
476
477 void suspendSessionOutput() throws IOException {
478 ioSession.getLock().lock();
479 try {
480 if (outbuf.hasData()) {
481 outbuf.flush(ioSession);
482 } else {
483 ioSession.clearEvent(SelectionKey.OP_WRITE);
484 }
485 } finally {
486 ioSession.getLock().unlock();
487 }
488 }
489
490 int streamOutput(final ByteBuffer src) throws IOException {
491 ioSession.getLock().lock();
492 try {
493 if (outgoingMessage == null) {
494 throw new ClosedChannelException();
495 }
496 final ContentEncoder contentEncoder = outgoingMessage.getBody();
497 final int bytesWritten = contentEncoder.write(src);
498 if (bytesWritten > 0) {
499 ioSession.setEvent(SelectionKey.OP_WRITE);
500 }
501 return bytesWritten;
502 } finally {
503 ioSession.getLock().unlock();
504 }
505 }
506
507 enum MessageDelineation { NONE, CHUNK_CODED, MESSAGE_HEAD}
508
509 MessageDelineation endOutputStream(final List<? extends Header> trailers) throws IOException {
510 ioSession.getLock().lock();
511 try {
512 if (outgoingMessage == null) {
513 return MessageDelineation.NONE;
514 }
515 final ContentEncoder contentEncoder = outgoingMessage.getBody();
516 contentEncoder.complete(trailers);
517 ioSession.setEvent(SelectionKey.OP_WRITE);
518 outgoingMessage = null;
519 return contentEncoder instanceof ChunkEncoder
520 ? MessageDelineation.CHUNK_CODED
521 : MessageDelineation.MESSAGE_HEAD;
522 } finally {
523 ioSession.getLock().unlock();
524 }
525 }
526
527 boolean isOutputCompleted() {
528 ioSession.getLock().lock();
529 try {
530 if (outgoingMessage == null) {
531 return true;
532 }
533 final ContentEncoder contentEncoder = outgoingMessage.getBody();
534 return contentEncoder.isCompleted();
535 } finally {
536 ioSession.getLock().unlock();
537 }
538 }
539
540 @Override
541 public void close() throws IOException {
542 ioSession.enqueue(ShutdownCommand.GRACEFUL, Command.Priority.NORMAL);
543 }
544
545 @Override
546 public void close(final CloseMode closeMode) {
547 ioSession.enqueue(new ShutdownCommand(closeMode), Command.Priority.IMMEDIATE);
548 }
549
550 @Override
551 public boolean isOpen() {
552 return connState == ConnectionState.ACTIVE;
553 }
554
555 @Override
556 public Timeout getSocketTimeout() {
557 return ioSession.getSocketTimeout();
558 }
559
560 @Override
561 public void setSocketTimeout(final Timeout timeout) {
562 ioSession.setSocketTimeout(timeout);
563 }
564
565 @Override
566 public EndpointDetails getEndpointDetails() {
567 if (endpointDetails == null) {
568 endpointDetails = new BasicEndpointDetails(
569 ioSession.getRemoteAddress(),
570 ioSession.getLocalAddress(),
571 connMetrics,
572 ioSession.getSocketTimeout());
573 }
574 return endpointDetails;
575 }
576
577 @Override
578 public ProtocolVersion getProtocolVersion() {
579 return version;
580 }
581
582 @Override
583 public SocketAddress getRemoteAddress() {
584 return ioSession.getRemoteAddress();
585 }
586
587 @Override
588 public SocketAddress getLocalAddress() {
589 return ioSession.getLocalAddress();
590 }
591
592 @Override
593 public SSLSession getSSLSession() {
594 final TlsDetails tlsDetails = ioSession.getTlsDetails();
595 return tlsDetails != null ? tlsDetails.getSSLSession() : null;
596 }
597
598 void appendState(final StringBuilder buf) {
599 buf.append("connState=").append(connState)
600 .append(", inbuf=").append(inbuf)
601 .append(", outbuf=").append(outbuf)
602 .append(", inputWindow=").append(capacityWindow != null ? capacityWindow.getWindow() : 0);
603 }
604
605 static class CapacityWindow implements CapacityChannel {
606 private final IOSession ioSession;
607 private final Object lock;
608 private int window;
609 private boolean closed;
610
611 CapacityWindow(final int window, final IOSession ioSession) {
612 this.window = window;
613 this.ioSession = ioSession;
614 this.lock = new Object();
615 }
616
617 @Override
618 public void update(final int increment) throws IOException {
619 synchronized (lock) {
620 if (closed) {
621 return;
622 }
623 if (increment > 0) {
624 updateWindow(increment);
625 ioSession.setEvent(SelectionKey.OP_READ);
626 }
627 }
628 }
629
630
631
632
633
634 int removeCapacity(final int delta) {
635 synchronized (lock) {
636 updateWindow(-delta);
637 if (window <= 0) {
638 ioSession.clearEvent(SelectionKey.OP_READ);
639 }
640 return window;
641 }
642 }
643
644 private void updateWindow(final int delta) {
645 int newValue = window + delta;
646
647 if (((window ^ newValue) & (delta ^ newValue)) < 0) {
648 newValue = delta < 0 ? Integer.MIN_VALUE : Integer.MAX_VALUE;
649 }
650 window = newValue;
651 }
652
653
654
655
656
657 void close() {
658 synchronized (lock) {
659 closed = true;
660 }
661 }
662
663
664 int getWindow() {
665 return window;
666 }
667 }
668 }