001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2017-2019 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.net;
020
021import java.net.InetSocketAddress;
022import java.net.SocketAddress;
023import java.nio.ByteBuffer;
024import java.security.KeyManagementException;
025import java.security.NoSuchAlgorithmException;
026import java.security.cert.X509Certificate;
027import java.util.Collections;
028import java.util.List;
029import java.util.Optional;
030import java.util.concurrent.ExecutionException;
031import java.util.concurrent.FutureTask;
032import java.util.logging.Level;
033import javax.net.ssl.ExtendedSSLSession;
034import javax.net.ssl.SNIServerName;
035import javax.net.ssl.SSLContext;
036import javax.net.ssl.SSLEngine;
037import javax.net.ssl.SSLEngineResult;
038import javax.net.ssl.SSLEngineResult.HandshakeStatus;
039import javax.net.ssl.SSLEngineResult.Status;
040import javax.net.ssl.SSLException;
041import javax.net.ssl.TrustManager;
042import javax.net.ssl.X509TrustManager;
043import org.jgrapes.core.Channel;
044import org.jgrapes.core.ClassChannel;
045import org.jgrapes.core.Component;
046import org.jgrapes.core.Components;
047import org.jgrapes.core.EventPipeline;
048import org.jgrapes.core.annotation.Handler;
049import org.jgrapes.core.annotation.HandlerDefinition.ChannelReplacements;
050import org.jgrapes.io.IOSubchannel;
051import org.jgrapes.io.events.Close;
052import org.jgrapes.io.events.Closed;
053import org.jgrapes.io.events.ConnectError;
054import org.jgrapes.io.events.HalfClosed;
055import org.jgrapes.io.events.IOError;
056import org.jgrapes.io.events.Input;
057import org.jgrapes.io.events.OpenSocketConnection;
058import org.jgrapes.io.events.Output;
059import org.jgrapes.io.events.Purge;
060import org.jgrapes.io.util.LinkedIOSubchannel;
061import org.jgrapes.io.util.ManagedBuffer;
062import org.jgrapes.io.util.ManagedBufferPool;
063import org.jgrapes.net.events.Accepted;
064import org.jgrapes.net.events.ClientConnected;
065import org.jgrapes.net.events.Connected;
066
067/**
068 * A component that receives and sends byte buffers on an
069 * encrypted channel and sends and receives the corresponding
070 * decrypted data on a plain channel.
071 * 
072 * The encrypted channel is assumed to be the network side
073 * ("upstream") and therefore {@link Input} events represent
074 * encrypted data and are decoded to {@link Output} events on
075 * the plain channel ("downstream") and vice versa.
076 */
077@SuppressWarnings({ "PMD.CouplingBetweenObjects" })
078public class SslCodec extends Component {
079
080    private final Channel encryptedChannel;
081    private final SSLContext sslContext;
082
083    /**
084     * Represents the encrypted channel in annotations.
085     */
086    private final class EncryptedChannel extends ClassChannel {
087    }
088
089    /**
090     * Creates a new codec that uses the given {@link SSLContext}.
091     * 
092     * @param plainChannel the component's channel
093     * @param encryptedChannel the channel with the encrypted data
094     * @param sslContext the SSL context to use
095     */
096    public SslCodec(Channel plainChannel, Channel encryptedChannel,
097            SSLContext sslContext) {
098        super(plainChannel, ChannelReplacements.create()
099            .add(EncryptedChannel.class, encryptedChannel));
100        this.encryptedChannel = encryptedChannel;
101        this.sslContext = sslContext;
102    }
103
104    /**
105     * Creates a new codec to be used as client.
106     * 
107     * @param plainChannel the component's channel
108     * @param encryptedChannel the channel with the encrypted data
109     * @param dontValidate if `true` accept all kinds of certificates
110     */
111    @SuppressWarnings({ "PMD.UncommentedEmptyMethodBody" })
112    public SslCodec(Channel plainChannel, Channel encryptedChannel,
113            boolean dontValidate) {
114        super(plainChannel, ChannelReplacements.create()
115            .add(EncryptedChannel.class, encryptedChannel));
116        this.encryptedChannel = encryptedChannel;
117        try {
118            final SSLContext sslContext = SSLContext.getInstance("TLSv1.3");
119            if (dontValidate) {
120                // Create a trust manager that does not validate certificate
121                // chains
122                final TrustManager[] trustAllCerts = {
123                    new X509TrustManager() {
124                        @Override
125                        public X509Certificate[] getAcceptedIssuers() {
126                            return new X509Certificate[0];
127                        }
128
129                        @Override
130                        public void checkClientTrusted(
131                                X509Certificate[] certs, String authType) {
132                        }
133
134                        @Override
135                        public void checkServerTrusted(
136                                X509Certificate[] certs, String authType) {
137                        }
138                    }
139                };
140                sslContext.init(null, trustAllCerts, null);
141            } else {
142                sslContext.init(null, null, null);
143            }
144            this.sslContext = sslContext;
145        } catch (NoSuchAlgorithmException | KeyManagementException e) {
146            throw new IllegalArgumentException(e);
147        }
148    }
149
150    /**
151     * Creates a new downstream connection as {@link LinkedIOSubchannel} 
152     * of the network connection together with an {@link SSLEngine}.
153     * 
154     * @param event
155     *            the accepted event
156     */
157    @Handler(channels = EncryptedChannel.class, excludeSelf = true)
158    public void onAccepted(Accepted event, IOSubchannel encryptedChannel) {
159        new PlainChannel(event, encryptedChannel);
160    }
161
162    /**
163     * Forward the connection request to the encrypted network.
164     *
165     * @param event the event
166     */
167    @Handler
168    public void onOpenConnection(OpenSocketConnection event) {
169        fire(new OpenSocketConnection(event.address())
170            .setAssociated(SslCodec.class, event), encryptedChannel);
171    }
172
173    /**
174     * Creates a new downstream connection as {@link LinkedIOSubchannel} 
175     * of the network connection together with an {@link SSLEngine}.
176     * 
177     * @param event
178     *            the accepted event
179     */
180    @Handler(channels = EncryptedChannel.class, excludeSelf = true)
181    public void onConnected(ClientConnected event,
182            IOSubchannel encryptedChannel) {
183        if (event.openEvent()
184            .associated(SslCodec.class, Object.class).isPresent()) {
185            new PlainChannel(event, encryptedChannel);
186        }
187    }
188
189    /**
190     * Handles encrypted data from upstream (the network). The data is 
191     * send through the {@link SSLEngine} and events are sent downstream 
192     * (and in the initial phases upstream) according to the conversion 
193     * results.
194     * 
195     * @param event the event
196     * @param encryptedChannel the channel for exchanging the encrypted data
197     * @throws InterruptedException 
198     * @throws SSLException 
199     * @throws ExecutionException 
200     */
201    @Handler(channels = EncryptedChannel.class, excludeSelf = true)
202    public void onInput(Input<ByteBuffer> event, IOSubchannel encryptedChannel)
203            throws InterruptedException, SSLException, ExecutionException {
204        @SuppressWarnings({ "unchecked", "PMD.AvoidDuplicateLiterals" })
205        final Optional<PlainChannel> plainChannel
206            = (Optional<PlainChannel>) LinkedIOSubchannel
207                .downstreamChannel(this, encryptedChannel);
208        if (plainChannel.isPresent()) {
209            plainChannel.get().sendDownstream(event);
210        }
211    }
212
213    /**
214     * Handles a half close event from the encrypted channel (client).
215     * 
216     * @param event the event
217     * @param encryptedChannel the channel for exchanging the encrypted data
218     * @throws InterruptedException 
219     * @throws SSLException 
220     */
221    @Handler(channels = EncryptedChannel.class, excludeSelf = true)
222    public void onHalfClosed(HalfClosed event, IOSubchannel encryptedChannel)
223            throws SSLException, InterruptedException {
224        @SuppressWarnings("unchecked")
225        final Optional<PlainChannel> plainChannel
226            = (Optional<PlainChannel>) LinkedIOSubchannel
227                .downstreamChannel(this, encryptedChannel);
228        if (plainChannel.isPresent()) {
229            plainChannel.get().upstreamHalfClosed();
230        }
231    }
232
233    /**
234     * Handles a close event from the encrypted channel (client).
235     * 
236     * @param event the event
237     * @param encryptedChannel the channel for exchanging the encrypted data
238     * @throws InterruptedException 
239     * @throws SSLException 
240     */
241    @Handler(channels = EncryptedChannel.class, excludeSelf = true)
242    public void onClosed(Closed<Void> event, IOSubchannel encryptedChannel)
243            throws SSLException, InterruptedException {
244        @SuppressWarnings("unchecked")
245        final Optional<PlainChannel> plainChannel
246            = (Optional<PlainChannel>) LinkedIOSubchannel
247                .downstreamChannel(this, encryptedChannel);
248        if (plainChannel.isPresent()) {
249            plainChannel.get().upstreamClosed();
250        }
251    }
252
253    /**
254     * Forwards a {@link Purge} event downstream.
255     *
256     * @param event the event
257     * @param encryptedChannel the encrypted channel
258     */
259    @Handler(channels = EncryptedChannel.class, excludeSelf = true)
260    public void onPurge(Purge event, IOSubchannel encryptedChannel) {
261        @SuppressWarnings("unchecked")
262        final Optional<PlainChannel> plainChannel
263            = (Optional<PlainChannel>) LinkedIOSubchannel
264                .downstreamChannel(this, encryptedChannel);
265        if (plainChannel.isPresent()) {
266            plainChannel.get().purge();
267        }
268    }
269
270    /**
271     * Handles an {@link IOError} event from the encrypted channel (client)
272     * by sending it downstream.
273     *
274     * @param event the event
275     * @throws SSLException the SSL exception
276     * @throws InterruptedException the interrupted exception
277     */
278    @Handler(channels = EncryptedChannel.class, excludeSelf = true)
279    @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
280    public void onIOError(IOError event)
281            throws SSLException, InterruptedException {
282        for (Channel channel : event.channels()) {
283            if (channel instanceof SocketIOChannel netConnChannel) {
284                @SuppressWarnings("unchecked")
285                final Optional<PlainChannel> plainChannel
286                    = (Optional<PlainChannel>) LinkedIOSubchannel
287                        .downstreamChannel(this, netConnChannel);
288                plainChannel.ifPresent(c -> fire(IOError.duplicate(event), c));
289                continue;
290            }
291
292            // Error while trying to establish the network connection
293            if (event.event() instanceof OpenSocketConnection openEvent) {
294                openEvent.associated(SslCodec.class, OpenSocketConnection.class)
295                    .ifPresent(
296                        e -> fire(new ConnectError(e, event.message()), this));
297            }
298        }
299    }
300
301    /**
302     * Sends plain data through the engine and then upstream.
303     * 
304     * @param event
305     *            the event with the data
306     * @throws InterruptedException if the execution was interrupted
307     * @throws SSLException if some SSL related problem occurs
308     * @throws ExecutionException 
309     */
310    @Handler
311    @SuppressWarnings("PMD.CompareObjectsWithEquals")
312    public void onOutput(Output<ByteBuffer> event, PlainChannel plainChannel)
313            throws InterruptedException, SSLException, ExecutionException {
314        if (plainChannel.hub() != this) {
315            return;
316        }
317        plainChannel.sendUpstream(event);
318    }
319
320    /**
321     * Forwards a close event upstream.
322     * 
323     * @param event
324     *            the close event
325     * @throws SSLException if an SSL related problem occurs
326     * @throws InterruptedException if the execution was interrupted
327     */
328    @Handler
329    @SuppressWarnings("PMD.CompareObjectsWithEquals")
330    public void onClose(Close event, PlainChannel plainChannel)
331            throws InterruptedException, SSLException {
332        if (plainChannel.hub() != this) {
333            return;
334        }
335        plainChannel.close(event);
336    }
337
338    /**
339     * Represents the plain channel.
340     */
341    @SuppressWarnings({ "PMD.PublicMemberInNonPublicType",
342        "PMD.AvoidSynchronizedStatement" })
343    private class PlainChannel extends LinkedIOSubchannel
344            implements SocketIOChannel {
345        public final SocketAddress localAddress;
346        public final SocketAddress remoteAddress;
347        public SSLEngine sslEngine;
348        private EventPipeline downPipeline;
349        private ManagedBufferPool<ManagedBuffer<ByteBuffer>,
350                ByteBuffer> downstreamPool;
351        private ByteBuffer carryOver;
352        private final boolean[] inputProcessed = { false };
353
354        /**
355         * Instantiates a new plain channel from an accepted connection.
356         *
357         * @param event the event
358         * @param upstreamChannel the upstream channel
359         */
360        @SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
361        public PlainChannel(Accepted event, IOSubchannel upstreamChannel) {
362            super(SslCodec.this, channel(), upstreamChannel,
363                newEventPipeline());
364            localAddress = event.localAddress();
365            remoteAddress = event.remoteAddress();
366            init();
367            sslEngine.setUseClientMode(false);
368        }
369
370        /**
371         * Instantiates a new plain channel from an established connection.
372         *
373         * @param event the event
374         * @param upstreamChannel the upstream channel
375         */
376        @SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
377        public PlainChannel(Connected<?> event, IOSubchannel upstreamChannel) {
378            super(SslCodec.this, channel(), upstreamChannel,
379                newEventPipeline());
380            localAddress = event.localAddress();
381            remoteAddress = event.remoteAddress();
382            init();
383            sslEngine.setUseClientMode(true);
384
385            // Forward downstream
386            if (event instanceof ClientConnected) {
387                downPipeline.fire(new ClientConnected(
388                    ((ClientConnected) event).openEvent().associated(
389                        SslCodec.class, OpenSocketConnection.class).get(),
390                    event.localAddress(), event.remoteAddress()), this);
391
392            } else {
393                downPipeline.fire(new Connected<>(
394                    event.localAddress(), event.remoteAddress()), this);
395            }
396        }
397
398        private void init() {
399            if (remoteAddress instanceof InetSocketAddress) {
400                sslEngine = sslContext.createSSLEngine(
401                    ((InetSocketAddress) remoteAddress).getAddress()
402                        .getHostAddress(),
403                    ((InetSocketAddress) remoteAddress).getPort());
404            } else {
405                sslEngine = sslContext.createSSLEngine();
406            }
407            String channelName = Components.objectName(SslCodec.this)
408                + "." + Components.objectName(this);
409            // Create buffer pools, adding 50 to decoded application buffer
410            // size, see
411            // https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/samples/sslengine/SSLEngineSimpleDemo.java
412            final int appBufSize
413                = sslEngine.getSession().getApplicationBufferSize();
414            downstreamPool = new ManagedBufferPool<>(ManagedBuffer::new,
415                () -> ByteBuffer.allocate(appBufSize + 50), 2)
416                    .setName(channelName + ".downstream.buffers");
417            // Provide buffers with application buffer size
418            // for use by downstream components.
419            setByteBufferPool(new ManagedBufferPool<>(ManagedBuffer::new,
420                () -> ByteBuffer.allocate(appBufSize), 2)
421                    .setName(channelName + ".upstream.buffers"));
422            downPipeline = newEventPipeline();
423            // Buffers for sending encrypted data upstream will be
424            // obtained from upstream() and resized if required.
425        }
426
427        /**
428         * Sends input downstream.
429         *
430         * @param event the event
431         * @throws SSLException the SSL exception
432         * @throws InterruptedException the interrupted exception
433         * @throws ExecutionException the execution exception
434         */
435        public void sendDownstream(Input<ByteBuffer> event)
436                throws SSLException, InterruptedException, ExecutionException {
437            ByteBuffer input = event.buffer().duplicate();
438            if (carryOver != null) {
439                if (carryOver.remaining() < input.remaining()) {
440                    // Shouldn't happen with carryOver having packet size
441                    // bytes left, have seen it happen nevertheless.
442                    carryOver.flip();
443                    ByteBuffer extCarryOver = ByteBuffer.allocate(
444                        carryOver.remaining() + input.remaining());
445                    extCarryOver.put(carryOver);
446                    carryOver = extCarryOver;
447                }
448                carryOver.put(input);
449                carryOver.flip();
450                input = carryOver;
451                carryOver = null;
452            }
453
454            // Main processing
455            processInput(input);
456
457            // Check if data from incomplete packet remains in input buffer
458            if (input.hasRemaining()) {
459                // Actually, packet buffer size should be sufficient,
460                // but since this is hard to test and doesn't really matter...
461                carryOver = ByteBuffer.allocate(input.remaining()
462                    + sslEngine.getSession().getPacketBufferSize() + 50);
463                carryOver.put(input);
464            }
465        }
466
467        @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NcssCount",
468            "PMD.CognitiveComplexity" })
469        private SSLEngineResult processInput(ByteBuffer input)
470                throws SSLException, InterruptedException, ExecutionException {
471            SSLEngineResult unwrapResult;
472            ManagedBuffer<ByteBuffer> unwrapped = downstreamPool.acquire();
473            while (true) {
474                unwrapResult
475                    = sslEngine.unwrap(input, unwrapped.backingBuffer());
476                synchronized (inputProcessed) {
477                    inputProcessed[0] = true;
478                    inputProcessed.notifyAll();
479                }
480                // Handle any handshaking procedures
481                switch (unwrapResult.getHandshakeStatus()) {
482                case NEED_TASK:
483                    while (true) {
484                        Runnable runnable = sslEngine.getDelegatedTask();
485                        if (runnable == null) {
486                            break;
487                        }
488                        // Having this handled by the response thread is
489                        // probably not really necessary, but as the delegated
490                        // task usually includes sending upstream...
491                        @SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
492                        FutureTask<Boolean> task
493                            = new FutureTask<>(runnable, true);
494                        upstreamChannel().responsePipeline()
495                            .executorService().submit(task);
496                        task.get();
497                    }
498                    continue;
499
500                case NEED_WRAP:
501                    ManagedBuffer<ByteBuffer> feedback
502                        = acquireUpstreamBuffer();
503                    synchronized (sslEngine) {
504                        SSLEngineResult wrapResult = sslEngine.wrap(
505                            ManagedBuffer.EMPTY_BYTE_BUFFER.backingBuffer(),
506                            feedback.backingBuffer());
507                        // JDK11 sometimes returns NEED_WRAP (together
508                        // with status is CLOSED) but does not produce
509                        // anything when wrapping (all of which does
510                        // not make sense).
511                        if (feedback.position() == 0
512                            && unwrapResult.getStatus() == Status.CLOSED) {
513                            feedback.unlockBuffer();
514                            break;
515                        }
516                        upstreamChannel()
517                            .respond(Output.fromSink(feedback, false));
518                        if (wrapResult
519                            .getHandshakeStatus() == HandshakeStatus.FINISHED) {
520                            fireAccepted();
521                        }
522                    }
523                    continue;
524
525                case FINISHED:
526                    fireAccepted();
527                    break;
528
529                default:
530                    break;
531                }
532
533                // Anything to forward downstream?
534                if (unwrapped.position() > 0) {
535                    // forward unwrapped data
536                    downPipeline.fire(Input.fromSink(unwrapped,
537                        sslEngine.isInboundDone()), this);
538                    unwrapped = null;
539                }
540
541                // If we have a buffer overflow or everything was okay
542                // and there's data left, we try again, else we quit.
543                if (unwrapResult.getStatus() != Status.BUFFER_OVERFLOW
544                    && (unwrapResult.getStatus() != Status.OK
545                        || !input.hasRemaining())) {
546                    // Underflow or closed
547                    if (unwrapped != null) {
548                        unwrapped.unlockBuffer();
549                    }
550                    break;
551                }
552
553                // Make sure we have an output buffer.
554                if (unwrapped == null) {
555                    unwrapped = downstreamPool.acquire();
556                }
557            }
558            return unwrapResult;
559        }
560
561        private void fireAccepted() {
562            List<SNIServerName> snis = Collections.emptyList();
563            if (sslEngine.getSession() instanceof ExtendedSSLSession) {
564                snis = ((ExtendedSSLSession) sslEngine.getSession())
565                    .getRequestedServerNames();
566            }
567            downPipeline.fire(new Accepted(
568                localAddress, remoteAddress, true, snis), this);
569        }
570
571        /**
572         * Send output upstream.
573         *
574         * @param event the event
575         * @throws SSLException the SSL exception
576         * @throws InterruptedException the interrupted exception
577         * @throws ExecutionException 
578         */
579        public void sendUpstream(Output<ByteBuffer> event)
580                throws SSLException, InterruptedException, ExecutionException {
581            ByteBuffer output = event.buffer().backingBuffer().duplicate();
582            processOutput(output, event.isEndOfRecord());
583        }
584
585        @SuppressWarnings("PMD.CognitiveComplexity")
586        private void processOutput(ByteBuffer output, boolean eor)
587                throws InterruptedException, SSLException, ExecutionException {
588            ManagedBuffer<ByteBuffer> wrapped = acquireUpstreamBuffer();
589            while (true) {
590                SSLEngineResult wrapResult;
591                // Cheap synchronization: no (relevant) input
592                inputProcessed[0] = false;
593                synchronized (sslEngine) {
594                    wrapResult
595                        = sslEngine.wrap(output, wrapped.backingBuffer());
596                    // Anything to be sent upstream?
597                    if (wrapped.position() > 0) {
598                        upstreamChannel().respond(Output.fromSink(wrapped,
599                            sslEngine.isInboundDone()
600                                || eor && !output.hasRemaining()));
601                        wrapped = null;
602                    }
603                }
604                switch (wrapResult.getHandshakeStatus()) {
605                case NEED_TASK:
606                    while (true) {
607                        Runnable runnable = sslEngine.getDelegatedTask();
608                        if (runnable == null) {
609                            break;
610                        }
611                        runnable.run();
612                    }
613                    continue;
614
615                case NEED_UNWRAP:
616                    // Input required. Wait until
617                    // input becomes available and retry.
618                    synchronized (inputProcessed) {
619                        while (!inputProcessed[0]) {
620                            inputProcessed.wait();
621                        }
622                    }
623                    break;
624
625                default:
626                    break;
627                }
628
629                // If we have a buffer overflow or everything was okay
630                // and there's data left, we try again, else we quit.
631                if (wrapResult.getStatus() != Status.BUFFER_OVERFLOW
632                    && (wrapResult.getStatus() != Status.OK
633                        || !output.hasRemaining())) {
634                    // Underflow or closed
635                    if (wrapped != null) {
636                        wrapped.unlockBuffer();
637                    }
638                    // Warn if data is discarded
639                    if (output.hasRemaining()) {
640                        logger.warning(() -> toString()
641                            + ": Upstream data discarded, SSLEngine status: "
642                            + wrapResult.getStatus());
643                    }
644                    break;
645                }
646
647                // Was handshake (or partial content), get new buffer and try
648                // again
649                if (wrapped == null) {
650                    wrapped = acquireUpstreamBuffer();
651                }
652            }
653        }
654
655        /**
656         * Close the connection.
657         *
658         * @param event the event
659         * @throws InterruptedException the interrupted exception
660         * @throws SSLException the SSL exception
661         */
662        public void close(Close event)
663                throws InterruptedException, SSLException {
664            sslEngine.closeOutbound();
665            while (!sslEngine.isOutboundDone()) {
666                ManagedBuffer<ByteBuffer> feedback = acquireUpstreamBuffer();
667                sslEngine.wrap(ManagedBuffer.EMPTY_BYTE_BUFFER
668                    .backingBuffer(), feedback.backingBuffer());
669                upstreamChannel().respond(Output.fromSink(feedback, false));
670            }
671            upstreamChannel().respond(new Close());
672        }
673
674        /**
675         * Handles the {@link HalfClosed} event.
676         *
677         * @throws SSLException the SSL exception
678         * @throws InterruptedException the interrupted exception
679         */
680        @SuppressWarnings("PMD.GuardLogStatement")
681        public void upstreamHalfClosed()
682                throws SSLException, InterruptedException {
683            if (sslEngine.isInboundDone()) {
684                // Was properly closed on SSL level
685                return;
686            }
687            try {
688                sslEngine.closeInbound();
689                sslEngine.closeOutbound();
690                while (!sslEngine.isOutboundDone()) {
691                    ManagedBuffer<ByteBuffer> feedback
692                        = acquireUpstreamBuffer();
693                    SSLEngineResult result = sslEngine.wrap(
694                        ManagedBuffer.EMPTY_BYTE_BUFFER.backingBuffer(),
695                        feedback.backingBuffer());
696                    // This is required for/since JDK 11. It claims that
697                    // outbound is not done, but doesn't produce any
698                    // additional
699                    // data.
700                    if (result.getStatus() == Status.CLOSED
701                        || feedback.position() == 0) {
702                        feedback.unlockBuffer();
703                        break;
704                    }
705                    upstreamChannel()
706                        .respond(Output.fromSink(feedback, false));
707                }
708            } catch (SSLException e) {
709                // Several clients (notably chromium, see
710                // https://bugs.chromium.org/p/chromium/issues/detail?id=118366
711                // don't close the connection properly. So nobody is really
712                // interested in this message
713                logger.log(Level.FINEST, e.getMessage(), e);
714            } catch (InterruptedException e) {
715                logger.log(Level.WARNING, e.getMessage(), e);
716            }
717        }
718
719        /**
720         * Forwards the {@link Closed} event downstream.
721         *
722         * @throws SSLException the SSL exception
723         * @throws InterruptedException the interrupted exception
724         */
725        public void upstreamClosed()
726                throws SSLException, InterruptedException {
727            downPipeline.fire(new Closed<>(), this);
728        }
729
730        private ManagedBuffer<ByteBuffer> acquireUpstreamBuffer()
731                throws InterruptedException {
732            ManagedBuffer<ByteBuffer> feedback
733                = upstreamChannel().byteBufferPool().acquire();
734            int encSize
735                = sslEngine.getSession().getPacketBufferSize() + 50;
736            if (feedback.capacity() < encSize) {
737                feedback.replaceBackingBuffer(ByteBuffer.allocate(
738                    encSize));
739            }
740            return feedback;
741        }
742
743        /**
744         * Fire a {@link Purge} event downstream.
745         */
746        public void purge() {
747            downPipeline.fire(new Purge(), this);
748        }
749
750        @Override
751        public SocketAddress localAddress() {
752            return localAddress;
753        }
754
755        @Override
756        public SocketAddress remoteAddress() {
757            return remoteAddress;
758        }
759
760        @Override
761        public boolean isPurgeable() {
762            return false;
763        }
764
765        @Override
766        public long purgeableSince() {
767            return 0;
768        }
769
770    }
771}