]> WPIA git - gigi.git/blob - lib/jetty/org/eclipse/jetty/io/ssl/SslConnection.java
[jetty]: Make SNI implementations possible.
[gigi.git] / lib / jetty / org / eclipse / jetty / io / ssl / SslConnection.java
1 //
2 //  ========================================================================
3 //  Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd.
4 //  ------------------------------------------------------------------------
5 //  All rights reserved. This program and the accompanying materials
6 //  are made available under the terms of the Eclipse Public License v1.0
7 //  and Apache License v2.0 which accompanies this distribution.
8 //
9 //      The Eclipse Public License is available at
10 //      http://www.eclipse.org/legal/epl-v10.html
11 //
12 //      The Apache License v2.0 is available at
13 //      http://www.opensource.org/licenses/apache2.0.php
14 //
15 //  You may elect to redistribute this code under either of these licenses.
16 //  ========================================================================
17 //
18
19 package org.eclipse.jetty.io.ssl;
20
21 import java.io.IOException;
22 import java.nio.ByteBuffer;
23 import java.nio.channels.ClosedChannelException;
24 import java.util.Arrays;
25 import java.util.concurrent.Executor;
26
27 import javax.net.ssl.SSLEngine;
28 import javax.net.ssl.SSLEngineResult;
29 import javax.net.ssl.SSLEngineResult.HandshakeStatus;
30 import javax.net.ssl.SSLEngineResult.Status;
31 import javax.net.ssl.SSLException;
32
33 import org.eclipse.jetty.io.AbstractConnection;
34 import org.eclipse.jetty.io.AbstractEndPoint;
35 import org.eclipse.jetty.io.ByteBufferPool;
36 import org.eclipse.jetty.io.Connection;
37 import org.eclipse.jetty.io.EndPoint;
38 import org.eclipse.jetty.io.EofException;
39 import org.eclipse.jetty.io.FillInterest;
40 import org.eclipse.jetty.io.RuntimeIOException;
41 import org.eclipse.jetty.io.SelectChannelEndPoint;
42 import org.eclipse.jetty.io.WriteFlusher;
43 import org.eclipse.jetty.util.BufferUtil;
44 import org.eclipse.jetty.util.Callback;
45 import org.eclipse.jetty.util.log.Log;
46 import org.eclipse.jetty.util.log.Logger;
47
48 /**
49  * A Connection that acts as an interceptor between an EndPoint providing SSL encrypted data
50  * and another consumer of an EndPoint (typically an {@link Connection} like HttpConnection) that
51  * wants unencrypted data.
52  * <p>
53  * The connector uses an {@link EndPoint} (typically {@link SelectChannelEndPoint}) as
54  * it's source/sink of encrypted data.   It then provides an endpoint via {@link #getDecryptedEndPoint()} to
55  * expose a source/sink of unencrypted data to another connection (eg HttpConnection).
56  * <p>
57  * The design of this class is based on a clear separation between the passive methods, which do not block nor schedule any
58  * asynchronous callbacks, and active methods that do schedule asynchronous callbacks.
59  * <p>
60  * The passive methods are {@link DecryptedEndPoint#fill(ByteBuffer)} and {@link DecryptedEndPoint#flush(ByteBuffer...)}. They make best
61  * effort attempts to progress the connection using only calls to the encrypted {@link EndPoint#fill(ByteBuffer)} and {@link EndPoint#flush(ByteBuffer...)}
62  * methods.  They will never block nor schedule any readInterest or write callbacks.   If a fill/flush cannot progress either because
63  * of network congestion or waiting for an SSL handshake message, then the fill/flush will simply return with zero bytes filled/flushed.
64  * Specifically, if a flush cannot proceed because it needs to receive a handshake message, then the flush will attempt to fill bytes from the
65  * encrypted endpoint, but if insufficient bytes are read it will NOT call {@link EndPoint#fillInterested(Callback)}.
66  * <p>
67  * It is only the active methods : {@link DecryptedEndPoint#fillInterested(Callback)} and
68  * {@link DecryptedEndPoint#write(Callback, ByteBuffer...)} that may schedule callbacks by calling the encrypted
69  * {@link EndPoint#fillInterested(Callback)} and {@link EndPoint#write(Callback, ByteBuffer...)}
70  * methods.  For normal data handling, the decrypted fillInterest method will result in an encrypted fillInterest and a decrypted
71  * write will result in an encrypted write. However, due to SSL handshaking requirements, it is also possible for a decrypted fill
72  * to call the encrypted write and for the decrypted flush to call the encrypted fillInterested methods.
73  * <p>
74  * MOST IMPORTANTLY, the encrypted callbacks from the active methods (#onFillable() and WriteFlusher#completeWrite()) do no filling or flushing
75  * themselves.  Instead they simple make the callbacks to the decrypted callbacks, so that the passive encrypted fill/flush will
76  * be called again and make another best effort attempt to progress the connection.
77  *
78  */
79 public class SslConnection extends AbstractConnection
80 {
81     private static final Logger LOG = Log.getLogger(SslConnection.class);
82     private static final boolean DEBUG = LOG.isDebugEnabled(); // Easy for the compiler to remove the code if DEBUG==false
83     private static final ByteBuffer __FILL_CALLED_FLUSH= BufferUtil.allocate(0);
84     private static final ByteBuffer __FLUSH_CALLED_FILL= BufferUtil.allocate(0);
85     private final ByteBufferPool _bufferPool;
86     private SSLEngine _sslEngine;
87     private final SslReconfigurator _sslFactory;
88     private final DecryptedEndPoint _decryptedEndPoint;
89     private ByteBuffer _decryptedInput;
90     private ByteBuffer _encryptedInput;
91     private ByteBuffer _encryptedOutput;
92     private final boolean _encryptedDirectBuffers = false;
93     private final boolean _decryptedDirectBuffers = false;
94     private final Runnable _runCompletWrite = new Runnable()
95     {
96         @Override
97         public void run()
98         {
99             _decryptedEndPoint.getWriteFlusher().completeWrite();
100         }
101     };
102     private boolean _renegotiationAllowed;
103
104     public SslConnection(ByteBufferPool byteBufferPool, Executor executor, EndPoint endPoint, SSLEngine sslEngine)
105     {
106         this(byteBufferPool, executor, endPoint, sslEngine, null);
107     }
108     public SslConnection(ByteBufferPool byteBufferPool, Executor executor, EndPoint endPoint, SSLEngine sslEngine, SslReconfigurator fact)
109     {
110         // This connection does not execute calls to onfillable, so they will be called by the selector thread.
111         // onfillable does not block and will only wakeup another thread to do the actual reading and handling.
112         super(endPoint, executor, !EXECUTE_ONFILLABLE);
113         this._bufferPool = byteBufferPool;
114         this._sslEngine = sslEngine;
115         this._sslFactory = fact;
116         this._decryptedEndPoint = newDecryptedEndPoint();
117     }
118
119     protected DecryptedEndPoint newDecryptedEndPoint()
120     {
121         return new DecryptedEndPoint();
122     }
123
124     public SSLEngine getSSLEngine()
125     {
126         return _sslEngine;
127     }
128
129     public DecryptedEndPoint getDecryptedEndPoint()
130     {
131         return _decryptedEndPoint;
132     }
133
134     public boolean isRenegotiationAllowed()
135     {
136         return _renegotiationAllowed;
137     }
138
139     public void setRenegotiationAllowed(boolean renegotiationAllowed)
140     {
141         this._renegotiationAllowed = renegotiationAllowed;
142     }
143
144     @Override
145     public void onOpen()
146     {
147         try
148         {
149             // Begin the handshake
150             _sslEngine.beginHandshake();
151             super.onOpen();
152             getDecryptedEndPoint().getConnection().onOpen();
153         }
154         catch (SSLException x)
155         {
156             getEndPoint().close();
157             throw new RuntimeIOException(x);
158         }
159     }
160
161     @Override
162     public void onClose()
163     {
164         _decryptedEndPoint.getConnection().onClose();
165         super.onClose();
166     }
167
168     @Override
169     public void close()
170     {
171         getDecryptedEndPoint().getConnection().close();
172     }
173
174     @Override
175     public void onFillable()
176     {
177         // onFillable means that there are encrypted bytes ready to be filled.
178         // however we do not fill them here on this callback, but instead wakeup
179         // the decrypted readInterest and/or writeFlusher so that they will attempt
180         // to do the fill and/or flush again and these calls will do the actually
181         // filling.
182
183         if (DEBUG)
184             LOG.debug("onFillable enter {}", _decryptedEndPoint);
185
186         // We have received a close handshake, close the end point to send FIN.
187         if (_decryptedEndPoint.isInputShutdown())
188             _decryptedEndPoint.close();
189
190         // wake up whoever is doing the fill or the flush so they can
191         // do all the filling, unwrapping, wrapping and flushing
192         _decryptedEndPoint.getFillInterest().fillable();
193
194         // If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read
195         synchronized(_decryptedEndPoint)
196         {
197             if (_decryptedEndPoint._flushRequiresFillToProgress)
198             {
199                 _decryptedEndPoint._flushRequiresFillToProgress = false;
200                 getExecutor().execute(_runCompletWrite);
201             }
202         }
203
204         if (DEBUG)
205             LOG.debug("onFillable exit {}", _decryptedEndPoint);
206     }
207
208     @Override
209     public void onFillInterestedFailed(Throwable cause)
210     {
211         // this means that the fill interest in encrypted bytes has failed.
212         // However we do not handle that here on this callback, but instead wakeup
213         // the decrypted readInterest and/or writeFlusher so that they will attempt
214         // to do the fill and/or flush again and these calls will do the actually
215         // handle the cause.
216         _decryptedEndPoint.getFillInterest().onFail(cause);
217
218         boolean failFlusher = false;
219         synchronized(_decryptedEndPoint)
220         {
221             if (_decryptedEndPoint._flushRequiresFillToProgress)
222             {
223                 _decryptedEndPoint._flushRequiresFillToProgress = false;
224                 failFlusher = true;
225             }
226         }
227         if (failFlusher)
228             _decryptedEndPoint.getWriteFlusher().onFail(cause);
229     }
230
231     @Override
232     public String toString()
233     {
234         ByteBuffer b = _encryptedInput;
235         int ei=b==null?-1:b.remaining();
236         b = _encryptedOutput;
237         int eo=b==null?-1:b.remaining();
238         b = _decryptedInput;
239         int di=b==null?-1:b.remaining();
240
241         return String.format("SslConnection@%x{%s,eio=%d/%d,di=%d} -> %s",
242                 hashCode(),
243                 _sslEngine.getHandshakeStatus(),
244                 ei,eo,di,
245                 _decryptedEndPoint.getConnection());
246     }
247
248     public class DecryptedEndPoint extends AbstractEndPoint
249     {
250         private boolean _fillRequiresFlushToProgress;
251         private boolean _flushRequiresFillToProgress;
252         private boolean _cannotAcceptMoreAppDataToFlush;
253         private boolean _handshaken;
254         private boolean _underFlown;
255         private boolean _peeking = _sslFactory != null;
256
257         private final Callback _writeCallback = new Callback()
258         {
259             @Override
260             public void succeeded()
261             {
262                 // This means that a write of encrypted data has completed.  Writes are done
263                 // only if there is a pending writeflusher or a read needed to write
264                 // data.  In either case the appropriate callback is passed on.
265                 boolean fillable = false;
266                 synchronized (DecryptedEndPoint.this)
267                 {
268                     if (DEBUG)
269                         LOG.debug("write.complete {}", SslConnection.this.getEndPoint());
270
271                     releaseEncryptedOutputBuffer();
272
273                     _cannotAcceptMoreAppDataToFlush = false;
274
275                     if (_fillRequiresFlushToProgress)
276                     {
277                         _fillRequiresFlushToProgress = false;
278                         fillable = true;
279                     }
280                 }
281                 if (fillable)
282                     getFillInterest().fillable();
283                 getExecutor().execute(_runCompletWrite);
284             }
285
286             @Override
287             public void failed(final Throwable x)
288             {
289                 // This means that a write of data has failed.  Writes are done
290                 // only if there is an active writeflusher or a read needed to write
291                 // data.  In either case the appropriate callback is passed on.
292                 boolean fail_filler = false;
293                 synchronized (DecryptedEndPoint.this)
294                 {
295                     if (DEBUG)
296                         LOG.debug("{} write.failed", SslConnection.this, x);
297                     BufferUtil.clear(_encryptedOutput);
298                     releaseEncryptedOutputBuffer();
299
300                     _cannotAcceptMoreAppDataToFlush = false;
301
302                     if (_fillRequiresFlushToProgress)
303                     {
304                         _fillRequiresFlushToProgress = false;
305                         fail_filler = true;
306                     }
307                 }
308
309                 final boolean filler_failed=fail_filler;
310
311                 failedCallback(new Callback()
312                 {
313                     @Override
314                     public void succeeded()
315                     {                        
316                     }
317
318                     @Override
319                     public void failed(Throwable x)
320                     {
321                         if (filler_failed)
322                             getFillInterest().onFail(x);
323                         getWriteFlusher().onFail(x);
324                     }
325                     
326                 },x);
327             }
328         };
329
330         public DecryptedEndPoint()
331         {
332             super(null,getEndPoint().getLocalAddress(), getEndPoint().getRemoteAddress());
333             setIdleTimeout(getEndPoint().getIdleTimeout());
334         }
335
336         @Override
337         protected FillInterest getFillInterest()
338         {
339             return super.getFillInterest();
340         }
341
342         @Override
343         public void setIdleTimeout(long idleTimeout)
344         {
345             super.setIdleTimeout(idleTimeout);
346             getEndPoint().setIdleTimeout(idleTimeout);
347         }
348
349         @Override
350         protected WriteFlusher getWriteFlusher()
351         {
352             return super.getWriteFlusher();
353         }
354
355         @Override
356         protected void onIncompleteFlush()
357         {
358             // This means that the decrypted endpoint write method was called and not
359             // all data could be wrapped. So either we need to write some encrypted data,
360             // OR if we are handshaking we need to read some encrypted data OR
361             // if neither then we should just try the flush again.
362             boolean flush = false;
363             synchronized (DecryptedEndPoint.this)
364             {
365                 if (DEBUG)
366                     LOG.debug("onIncompleteFlush {}", getEndPoint());
367                 // If we have pending output data,
368                 if (BufferUtil.hasContent(_encryptedOutput))
369                 {
370                     // write it
371                     _cannotAcceptMoreAppDataToFlush = true;
372                     getEndPoint().write(_writeCallback, _encryptedOutput);
373                 }
374                 // If we are handshaking and need to read,
375                 else if (_sslEngine.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP)
376                 {
377                     // check if we are actually read blocked in order to write
378                     _flushRequiresFillToProgress = true;
379                     SslConnection.this.fillInterested();
380                 }
381                 else
382                 {
383                     flush = true;
384                 }
385             }
386             if (flush)
387             {
388                 // If the output is closed,
389                 if (isOutputShutdown())
390                 {
391                     // don't bother writing, just notify of close
392                     getWriteFlusher().onClose();
393                 }
394                 // Else,
395                 else
396                 {
397                     // try to flush what is pending
398                     getWriteFlusher().completeWrite();
399                 }
400             }
401         }
402
403         @Override
404         protected boolean needsFill() throws IOException
405         {
406             // This means that the decrypted data consumer has called the fillInterested
407             // method on the DecryptedEndPoint, so we have to work out if there is
408             // decrypted data to be filled or what callbacks to setup to be told when there
409             // might be more encrypted data available to attempt another call to fill
410
411             synchronized (DecryptedEndPoint.this)
412             {
413                 // Do we already have some app data, then app can fill now so return true
414                 if (BufferUtil.hasContent(_decryptedInput))
415                     return true;
416
417                 // If we have no encrypted data to decrypt OR we have some, but it is not enough
418                 if (BufferUtil.isEmpty(_encryptedInput) || _underFlown)
419                 {
420                     // We are not ready to read data
421
422                     // Are we actually write blocked?
423                     if (_fillRequiresFlushToProgress)
424                     {
425                         // we must be blocked trying to write before we can read
426
427                         // Do we have data to write
428                         if (BufferUtil.hasContent(_encryptedOutput))
429                         {
430                             // write it
431                             _cannotAcceptMoreAppDataToFlush = true;
432                             getEndPoint().write(_writeCallback, _encryptedOutput);
433                         }
434                         else
435                         {
436                             // we have already written the net data
437                             // pretend we are readable so the wrap is done by next readable callback
438                             _fillRequiresFlushToProgress = false;
439                             return true;
440                         }
441                     }
442                     else
443                     {
444                         // Normal readable callback
445                         // Get called back on onfillable when then is more data to fill
446                         SslConnection.this.fillInterested();
447                     }
448
449                     return false;
450                 }
451                 else
452                 {
453                     // We are ready to read data
454                     return true;
455                 }
456             }
457         }
458
459         @Override
460         public void setConnection(Connection connection)
461         {
462             if (connection instanceof AbstractConnection)
463             {
464                 AbstractConnection a = (AbstractConnection)connection;
465                 if (a.getInputBufferSize()<_sslEngine.getSession().getApplicationBufferSize())
466                     a.setInputBufferSize(_sslEngine.getSession().getApplicationBufferSize());
467             }
468             super.setConnection(connection);
469         }
470
471         public SslConnection getSslConnection()
472         {
473             return SslConnection.this;
474         }
475
476         @Override
477         public synchronized int fill(ByteBuffer buffer) throws IOException
478         {
479             if (DEBUG)
480                 LOG.debug("{} fill enter", SslConnection.this);
481             try
482             {
483                 // Do we already have some decrypted data?
484                 if (BufferUtil.hasContent(_decryptedInput))
485                     return BufferUtil.append(buffer,_decryptedInput);
486
487                 // We will need a network buffer
488                 if (_encryptedInput == null)
489                     _encryptedInput = _bufferPool.acquire(_sslEngine.getSession().getPacketBufferSize(), _encryptedDirectBuffers);
490                 else if(!_peeking)
491                     BufferUtil.compact(_encryptedInput);
492
493                 // We also need an app buffer, but can use the passed buffer if it is big enough
494                 ByteBuffer app_in;
495                 if (BufferUtil.space(buffer) > _sslEngine.getSession().getApplicationBufferSize())
496                     app_in = buffer;
497                 else if (_decryptedInput == null)
498                     app_in = _decryptedInput = _bufferPool.acquire(_sslEngine.getSession().getApplicationBufferSize(), _decryptedDirectBuffers);
499                 else
500                     app_in = _decryptedInput;
501
502                 // loop filling and unwrapping until we have something
503                 while (true)
504                 {
505                     // Let's try reading some encrypted data... even if we have some already.
506                     int net_filled = getEndPoint().fill(_encryptedInput);
507                     if (DEBUG)
508                         LOG.debug("{} filled {} encrypted bytes", SslConnection.this, net_filled);
509
510                     decryption: while (true)
511                     {
512                         // Let's unwrap even if we have no net data because in that
513                         // case we want to fall through to the handshake handling
514                         int pos = BufferUtil.flipToFill(app_in);
515                         SSLEngineResult unwrapResult = _sslEngine.unwrap(_encryptedInput, app_in);
516                         BufferUtil.flipToFlush(app_in, pos);
517                         if (DEBUG)
518                             LOG.debug("{} unwrap {}", SslConnection.this, unwrapResult);
519
520                         HandshakeStatus handshakeStatus = _sslEngine.getHandshakeStatus();
521                         HandshakeStatus unwrapHandshakeStatus = unwrapResult.getHandshakeStatus();
522                         Status unwrapResultStatus = unwrapResult.getStatus();
523
524                         _underFlown = unwrapResultStatus == Status.BUFFER_UNDERFLOW;
525
526                         if (_underFlown)
527                         {
528                             if (net_filled < 0)
529                                 closeInbound();
530                             if (net_filled <= 0)
531                                 return net_filled;
532                         }
533
534                         switch (unwrapResultStatus)
535                         {
536                             case CLOSED:
537                             {
538                                 switch (handshakeStatus)
539                                 {
540                                     case NOT_HANDSHAKING:
541                                     {
542                                         // We were not handshaking, so just tell the app we are closed
543                                         return -1;
544                                     }
545                                     case NEED_TASK:
546                                     {
547                                         _sslEngine.getDelegatedTask().run();
548                                         continue;
549                                     }
550                                     case NEED_WRAP:
551                                     {
552                                         // We need to send some handshake data (probably the close handshake).
553                                         // We return -1 so that the application can drive the close by flushing
554                                         // or shutting down the output.
555                                         return -1;
556                                     }
557                                     default:
558                                     {
559                                         throw new IllegalStateException();
560                                     }
561                                 }
562                             }
563                             case BUFFER_UNDERFLOW:
564                             case OK:
565                             {
566                                 if (unwrapHandshakeStatus == HandshakeStatus.FINISHED && !_handshaken)
567                                 {
568                                     _handshaken = true;
569                                     if (DEBUG)
570                                         LOG.debug("{} {} handshake completed", SslConnection.this,
571                                                 _sslEngine.getUseClientMode() ? "client-side" : "resumed session server-side");
572                                 }
573
574                                 // Check whether renegotiation is allowed
575                                 if (_handshaken && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING && !isRenegotiationAllowed())
576                                 {
577                                     if (DEBUG)
578                                         LOG.debug("{} renegotiation denied", SslConnection.this);
579                                     closeInbound();
580                                     return -1;
581                                 }
582
583                                 // If bytes were produced, don't bother with the handshake status;
584                                 // pass the decrypted data to the application, which will perform
585                                 // another call to fill() or flush().
586                                 if (unwrapResult.bytesProduced() > 0)
587                                 {
588                                     if (app_in == buffer)
589                                         return unwrapResult.bytesProduced();
590                                     return BufferUtil.append(buffer,_decryptedInput);
591                                 }
592
593                                 switch (handshakeStatus)
594                                 {
595                                     case NOT_HANDSHAKING:
596                                     {
597                                         if (_underFlown)
598                                             break decryption;
599                                         continue;
600                                     }
601                                     case NEED_TASK:
602                                     {
603                                         _sslEngine.getDelegatedTask().run();
604                                         if(_peeking)
605                                         {
606                                                 _sslEngine = _sslFactory.restartSSL(_sslEngine.getHandshakeSession());
607                                                 _encryptedInput.position(0);
608                                                 _peeking = false;
609                                                 continue decryption;
610                                         }
611                                         continue;
612                                     }
613                                     case NEED_WRAP:
614                                     {
615                                         // If we are called from flush()
616                                         // return to let it do the wrapping.
617                                         if (buffer == __FLUSH_CALLED_FILL)
618                                             return 0;
619
620                                         _fillRequiresFlushToProgress = true;
621                                         flush(__FILL_CALLED_FLUSH);
622                                         if (BufferUtil.isEmpty(_encryptedOutput))
623                                         {
624                                             // The flush wrote all the encrypted bytes so continue to fill
625                                             _fillRequiresFlushToProgress = false;
626                                             continue;
627                                         }
628                                         else
629                                         {
630                                             // The flush did not complete, return from fill()
631                                             // and let the write completion mechanism to kick in.
632                                             return 0;
633                                         }
634                                     }
635                                     case NEED_UNWRAP:
636                                     {
637                                         if (_underFlown)
638                                             break decryption;
639                                         continue;
640                                     }
641                                     default:
642                                     {
643                                         throw new IllegalStateException();
644                                     }
645                                 }
646                             }
647                             default:
648                             {
649                                 throw new IllegalStateException();
650                             }
651                         }
652                     }
653                 }
654             }
655             catch (Exception e)
656             {
657                 getEndPoint().close();
658                 throw e;
659             }
660             finally
661             {
662                 // If we are handshaking, then wake up any waiting write as well as it may have been blocked on the read
663                 if (_flushRequiresFillToProgress)
664                 {
665                     _flushRequiresFillToProgress = false;
666                     getExecutor().execute(_runCompletWrite);
667                 }
668
669                 if (_encryptedInput != null && !_encryptedInput.hasRemaining())
670                 {
671                     _bufferPool.release(_encryptedInput);
672                     _encryptedInput = null;
673                 }
674                 if (_decryptedInput != null && !_decryptedInput.hasRemaining())
675                 {
676                     _bufferPool.release(_decryptedInput);
677                     _decryptedInput = null;
678                 }
679                 if (DEBUG)
680                     LOG.debug("{} fill exit", SslConnection.this);
681             }
682         }
683
684         private void closeInbound()
685         {
686             try
687             {
688                 _sslEngine.closeInbound();
689             }
690             catch (SSLException x)
691             {
692                 LOG.ignore(x);
693             }
694         }
695
696         @Override
697         public synchronized boolean flush(ByteBuffer... appOuts) throws IOException
698         {
699             // The contract for flush does not require that all appOuts bytes are written
700             // or even that any appOut bytes are written!  If the connection is write block
701             // or busy handshaking, then zero bytes may be taken from appOuts and this method
702             // will return 0 (even if some handshake bytes were flushed and filled).
703             // it is the applications responsibility to call flush again - either in a busy loop
704             // or better yet by using EndPoint#write to do the flushing.
705
706             if (DEBUG)
707                 LOG.debug("{} flush enter {}", SslConnection.this, Arrays.toString(appOuts));
708             int consumed=0;
709             try
710             {
711                 if (_cannotAcceptMoreAppDataToFlush)
712                 {
713                     if (_sslEngine.isOutboundDone())
714                         throw new EofException(new ClosedChannelException());
715                     return false;
716                 }
717
718                 // We will need a network buffer
719                 if (_encryptedOutput == null)
720                     _encryptedOutput = _bufferPool.acquire(_sslEngine.getSession().getPacketBufferSize(), _encryptedDirectBuffers);
721
722                 while (true)
723                 {
724                     // We call sslEngine.wrap to try to take bytes from appOut buffers and encrypt them into the _netOut buffer
725                     BufferUtil.compact(_encryptedOutput);
726                     int pos = BufferUtil.flipToFill(_encryptedOutput);
727                     SSLEngineResult wrapResult = _sslEngine.wrap(appOuts, _encryptedOutput);
728                     if (DEBUG)
729                         LOG.debug("{} wrap {}", SslConnection.this, wrapResult);
730                     BufferUtil.flipToFlush(_encryptedOutput, pos);
731                     if (wrapResult.bytesConsumed()>0)
732                         consumed+=wrapResult.bytesConsumed();
733
734                     boolean allConsumed=true;
735                     // clear empty buffers to prevent position creeping up the buffer
736                     for (ByteBuffer b : appOuts)
737                     {
738                         if (BufferUtil.isEmpty(b))
739                             BufferUtil.clear(b);
740                         else
741                             allConsumed=false;
742                     }
743
744                     Status wrapResultStatus = wrapResult.getStatus();
745
746                     // and deal with the results returned from the sslEngineWrap
747                     switch (wrapResultStatus)
748                     {
749                         case CLOSED:
750                             // The SSL engine has close, but there may be close handshake that needs to be written
751                             if (BufferUtil.hasContent(_encryptedOutput))
752                             {
753                                 _cannotAcceptMoreAppDataToFlush = true;
754                                 getEndPoint().flush(_encryptedOutput);
755                                 getEndPoint().shutdownOutput();
756                                 // If we failed to flush the close handshake then we will just pretend that
757                                 // the write has progressed normally and let a subsequent call to flush
758                                 // (or WriteFlusher#onIncompleteFlushed) to finish writing the close handshake.
759                                 // The caller will find out about the close on a subsequent flush or fill.
760                                 if (BufferUtil.hasContent(_encryptedOutput))
761                                     return false;
762                             }
763                             // otherwise we have written, and the caller will close the underlying connection
764                             else
765                             {
766                                 getEndPoint().shutdownOutput();
767                             }
768                             return allConsumed;
769
770                         case BUFFER_UNDERFLOW:
771                             throw new IllegalStateException();
772
773                         default:
774                             if (DEBUG)
775                                 LOG.debug("{} {} {}", this, wrapResultStatus, BufferUtil.toDetailString(_encryptedOutput));
776
777                             if (wrapResult.getHandshakeStatus() == HandshakeStatus.FINISHED && !_handshaken)
778                             {
779                                 _handshaken = true;
780                                 if (DEBUG)
781                                     LOG.debug("{} {} handshake completed", SslConnection.this, "server-side");
782                             }
783
784                             HandshakeStatus handshakeStatus = _sslEngine.getHandshakeStatus();
785
786                             // Check whether renegotiation is allowed
787                             if (_handshaken && handshakeStatus != HandshakeStatus.NOT_HANDSHAKING && !isRenegotiationAllowed())
788                             {
789                                 if (DEBUG)
790                                     LOG.debug("{} renegotiation denied", SslConnection.this);
791                                 shutdownOutput();
792                                 return allConsumed;
793                             }
794
795                             // if we have net bytes, let's try to flush them
796                             if (BufferUtil.hasContent(_encryptedOutput))
797                                 getEndPoint().flush(_encryptedOutput);
798
799                             // But we also might have more to do for the handshaking state.
800                             switch (handshakeStatus)
801                             {
802                                 case NOT_HANDSHAKING:
803                                     // Return with the number of bytes consumed (which may be 0)
804                                     return allConsumed && BufferUtil.isEmpty(_encryptedOutput);
805
806                                 case NEED_TASK:
807                                     // run the task and continue
808                                     _sslEngine.getDelegatedTask().run();
809                                     continue;
810
811                                 case NEED_WRAP:
812                                     // Hey we just wrapped! Oh well who knows what the sslEngine is thinking, so continue and we will wrap again
813                                     continue;
814
815                                 case NEED_UNWRAP:
816                                     // Ah we need to fill some data so we can write.
817                                     // So if we were not called from fill and the app is not reading anyway
818                                     if (appOuts[0]!=__FILL_CALLED_FLUSH && !getFillInterest().isInterested())
819                                     {
820                                         // Tell the onFillable method that there might be a write to complete
821                                         _flushRequiresFillToProgress = true;
822                                         fill(__FLUSH_CALLED_FILL);
823                                         // Check if after the fill() we need to wrap again
824                                         if (handshakeStatus == HandshakeStatus.NEED_WRAP)
825                                             continue;
826                                     }
827                                     return allConsumed && BufferUtil.isEmpty(_encryptedOutput);
828
829                                 case FINISHED:
830                                     throw new IllegalStateException();
831                             }
832                     }
833                 }
834             }
835             catch (Exception e)
836             {
837                 getEndPoint().close();
838                 throw e;
839             }
840             finally
841             {
842                 if (DEBUG)
843                     LOG.debug("{} flush exit, consumed {}", SslConnection.this, consumed);
844                 releaseEncryptedOutputBuffer();
845             }
846         }
847
848         private void releaseEncryptedOutputBuffer()
849         {
850             if (!Thread.holdsLock(DecryptedEndPoint.this))
851                 throw new IllegalStateException();
852             if (_encryptedOutput != null && !_encryptedOutput.hasRemaining())
853             {
854                 _bufferPool.release(_encryptedOutput);
855                 _encryptedOutput = null;
856             }
857         }
858
859         @Override
860         public void shutdownOutput()
861         {
862             boolean ishut = isInputShutdown();
863             boolean oshut = isOutputShutdown();
864             if (DEBUG)
865                 LOG.debug("{} shutdownOutput: oshut={}, ishut={}", SslConnection.this, oshut, ishut);
866             if (ishut)
867             {
868                 // Aggressively close, since inbound close alert has already been processed
869                 // and the TLS specification allows to close the connection directly, which
870                 // is what most other implementations expect: a FIN rather than a TLS close
871                 // reply. If a TLS close reply is sent, most implementations send a RST.
872                 getEndPoint().close();
873             }
874             else if (!oshut)
875             {
876                 try
877                 {
878                     _sslEngine.closeOutbound();
879                     flush(BufferUtil.EMPTY_BUFFER); // Send close handshake
880                     SslConnection.this.fillInterested(); // seek reply FIN or RST or close handshake
881                 }
882                 catch (Exception e)
883                 {
884                     LOG.ignore(e);
885                     getEndPoint().close();
886                 }
887             }
888         }
889
890         @Override
891         public boolean isOutputShutdown()
892         {
893             return _sslEngine.isOutboundDone() || getEndPoint().isOutputShutdown();
894         }
895
896         @Override
897         public void close()
898         {
899             super.close();
900             // First send the TLS Close Alert, then the FIN
901             shutdownOutput();
902             getEndPoint().close();
903         }
904
905         @Override
906         public boolean isOpen()
907         {
908             return getEndPoint().isOpen();
909         }
910
911         @Override
912         public Object getTransport()
913         {
914             return getEndPoint();
915         }
916
917         @Override
918         public boolean isInputShutdown()
919         {
920             return _sslEngine.isInboundDone();
921         }
922
923         @Override
924         public String toString()
925         {
926             return super.toString()+"->"+getEndPoint().toString();
927         }
928     }
929 }