Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 5eb30172a10bbd21b2d4c544d52b707a040062fa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
// ========================================================================
// Copyright (c) 2004-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================

package org.eclipse.jetty.io.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;

import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.Buffers;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

/* ------------------------------------------------------------ */
/**
 * SslSelectChannelEndPoint
 * <p>
 * A SelectChannelEndPoint that uses an {@link SSLEngine} to handle an
 * SSL connection.
 * <p>
 * There is a named logger "org.eclipse.jetty.http.ssl"
 * </p>
 */
public class SslSelectChannelEndPoint extends SelectChannelEndPoint
{
    static Logger __log = Log.getLogger("org.eclipse.jetty.http.ssl");

    private static final ByteBuffer[] __NO_BUFFERS={};

    private final Buffers _buffers;

    private final SSLEngine _engine;
    private final SSLSession _session;
    private volatile NIOBuffer _inNIOBuffer;
    private volatile NIOBuffer _outNIOBuffer;

    private final ByteBuffer[] _gather=new ByteBuffer[2];

    private boolean _closing=false;
    private SSLEngineResult _result;

    private boolean _handshook=false;
    private boolean _allowRenegotiate=false;

    private final boolean _debug = __log.isDebugEnabled(); // snapshot debug status for optimizer

    /* ------------------------------------------------------------ */
    public SslSelectChannelEndPoint(Buffers buffers,SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey key, SSLEngine engine, int maxIdleTime)
            throws IOException
    {
        super(channel,selectSet,key, maxIdleTime);
        _buffers=buffers;

        // ssl
        _engine=engine;
        _session=engine.getSession();

        if (_debug) __log.debug(_session+" channel="+channel);
    }

    /* ------------------------------------------------------------ */
    public SslSelectChannelEndPoint(Buffers buffers,SocketChannel channel, SelectorManager.SelectSet selectSet, SelectionKey key, SSLEngine engine)
            throws IOException
    {
        super(channel,selectSet,key);
        _buffers=buffers;

        // ssl
        _engine=engine;
        _session=engine.getSession();

        if (_debug) __log.debug(_session+" channel="+channel);
    }

    int _outCount;

    /* ------------------------------------------------------------ */
    private void needOutBuffer()
    {
        synchronized (this)
        {
            _outCount++;
            if (_outNIOBuffer==null)
                _outNIOBuffer=(NIOBuffer)_buffers.getBuffer(_session.getPacketBufferSize());
        }
    }

    /* ------------------------------------------------------------ */
    private void freeOutBuffer()
    {
        synchronized (this)
        {
            if (--_outCount<=0 && _outNIOBuffer!=null && _outNIOBuffer.length()==0)
            {
                _buffers.returnBuffer(_outNIOBuffer);
                _outNIOBuffer=null;
                _outCount=0;
            }
        }
    }

    int _inCount;
    /* ------------------------------------------------------------ */
    private void needInBuffer()
    {
        synchronized (this)
        {
            _inCount++;
            if(_inNIOBuffer==null)
                _inNIOBuffer=(NIOBuffer)_buffers.getBuffer(_session.getPacketBufferSize());
        }
    }

    /* ------------------------------------------------------------ */
    private void freeInBuffer()
    {
        synchronized (this)
        {
            if (--_inCount<=0 &&_inNIOBuffer!=null && _inNIOBuffer.length()==0)
            {
                _buffers.returnBuffer(_inNIOBuffer);
                _inNIOBuffer=null;
                _inCount=0;
            }
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * @return True if SSL re-negotiation is allowed (default false)
     */
    public boolean isAllowRenegotiate()
    {
        return _allowRenegotiate;
    }

    /* ------------------------------------------------------------ */
    /**
     * Set if SSL re-negotiation is allowed. CVE-2009-3555 discovered
     * a vulnerability in SSL/TLS with re-negotiation.  If your JVM
     * does not have CVE-2009-3555 fixed, then re-negotiation should
     * not be allowed.
     * @param allowRenegotiate true if re-negotiation is allowed (default false)
     */
    public void setAllowRenegotiate(boolean allowRenegotiate)
    {
        _allowRenegotiate = allowRenegotiate;
    }


    /* ------------------------------------------------------------ */
    @Override
    public boolean isOutputShutdown()
    {
        return _engine!=null && _engine.isOutboundDone();
    }

    /* ------------------------------------------------------------ */
    @Override
    public boolean isInputShutdown()
    {
        return _engine!=null && _engine.isInboundDone();
    }

    /* ------------------------------------------------------------ */
    @Override
    public void shutdownOutput() throws IOException
    {
        sslClose();
        super.shutdownOutput();
    }

    /* ------------------------------------------------------------ */
    protected void sslClose() throws IOException
    {
        if (_closing)
            return;
        _closing=true;

        // TODO - this really should not be done in a loop here - but with async callbacks.
        long end=System.currentTimeMillis()+getMaxIdleTime();
        try
        {
            while (isOpen() && isBufferingOutput()&& System.currentTimeMillis()<end)
            {
                flush();
                if (isBufferingOutput())
                {
                    Thread.sleep(50); // TODO non blocking
                    flush();
                }
            }

            _engine.closeOutbound();

            loop: while (isOpen() && !(_engine.isInboundDone() && _engine.isOutboundDone()) && System.currentTimeMillis()<end)
            {
                while (isOpen() && isBufferingOutput() && System.currentTimeMillis()<end)
                {
                    flush();
                    if (isBufferingOutput())
                        Thread.sleep(50);
                }

                if (_debug) __log.debug(_session+" closing "+_engine.getHandshakeStatus());
                switch(_engine.getHandshakeStatus())
                {
                    case FINISHED:
                    case NOT_HANDSHAKING:
                        _handshook=true;
                        break loop;

                    case NEED_UNWRAP:
                        Buffer buffer =_buffers.getBuffer(_engine.getSession().getApplicationBufferSize());
                        try
                        {
                            ByteBuffer bbuffer = ((NIOBuffer)buffer).getByteBuffer();
                            if (!unwrap(bbuffer) && _engine.getHandshakeStatus()==HandshakeStatus.NEED_UNWRAP)
                            {
                                break loop;
                            }
                        }
                        catch(SSLException e)
                        {
                            super.close();
                            Log.ignore(e);
                        }
                        finally
                        {
                            _buffers.returnBuffer(buffer);
                        }
                        break;

                    case NEED_TASK:
                    {
                        Runnable task;
                        while ((task=_engine.getDelegatedTask())!=null)
                        {
                            task.run();
                        }
                        break;
                    }

                    case NEED_WRAP:
                    {
                        needOutBuffer();
                        ByteBuffer out_buffer=_outNIOBuffer.getByteBuffer();
                        try
                        {
                            if (_outNIOBuffer.length()>0)
                                flush();
                            _outNIOBuffer.compact();
                            int put=_outNIOBuffer.putIndex();
                            out_buffer.position(put);
                            _result=null;
                            _result=_engine.wrap(__NO_BUFFERS,out_buffer);
                            if (_debug) __log.debug(_session+" close wrap "+_result);
                            _outNIOBuffer.setPutIndex(put+_result.bytesProduced());
                        }
                        catch(SSLException e)
                        {
                            super.close();
                            throw e;
                        }
                        finally
                        {
                            out_buffer.position(0);
                            freeOutBuffer();
                        }

                        break;
                    }
                }
            }
        }
        catch (Exception e)
        {
            Log.debug(e);
            super.close();
        }
    }

    /* ------------------------------------------------------------ */
    @Override
    public void close() throws IOException
    {
        sslClose();
        super.close();
    }

    /* ------------------------------------------------------------ */
    /** Fill the buffer with unencrypted bytes.
     * Called by a Http Parser when more data is
     * needed to continue parsing a request or a response.
     */
    @Override
    public int fill(Buffer buffer) throws IOException
    {
        // This end point only works on NIO buffer type (director
        // or indirect), so extract the NIO buffer that is wrapped
        // by the passed jetty Buffer.
        final ByteBuffer bbuf=extractInputBuffer(buffer);

        // remember the original size of the unencrypted buffer
        int size=buffer.length();

        HandshakeStatus initialStatus = _engine.getHandshakeStatus();
        //noinspection SynchronizationOnLocalVariableOrMethodParameter
        synchronized (bbuf)
        {
            try
            {
                // Call the SSLEngine unwrap method to process data in
                // the inBuffer.  If there is no data in the inBuffer, then
                // super.fill is called to read encrypted bytes.
                unwrap(bbuf);

                // Loop through the SSL engine state machine

                int wraps=0;
                loop: while (true)
                {
                    // If we have encrypted data in output buffer
                    if (isBufferingOutput())
                    {
                        // we must flush it, as the other end might be
                        // waiting for that outgoing data before sending
                        // more incoming data
                        flush();

                        // If we were unable to flush all the data, then
                        // we should break the loop and wait for the call
                        // back to handle when the SelectSet detects that
                        // the channel is writable again.
                        if (isBufferingOutput())
                            break loop;
                    }

                    // handle the current hand share status
                    switch(_engine.getHandshakeStatus())
                    {
                        case FINISHED:
                        case NOT_HANDSHAKING:
                            // If we are closing, then unwrap must have CLOSED result,
                            // so return -1 to signal upwards
                            if (_closing)
                                return -1;

                            // otherwise we break loop with the data we have unwrapped.
                            break loop;

                        case NEED_UNWRAP:
                            checkRenegotiate();
                            // Need more data to be unwrapped so try another call to unwrap
                            if (!unwrap(bbuf) && _engine.getHandshakeStatus()==HandshakeStatus.NEED_UNWRAP)
                            {
                                // If the unwrap call did not make any progress and we are still in
                                // NEED_UNWRAP, then we should break the loop and wait for more data to
                                // arrive.
                                break loop;
                            }
                            // progress was made so continue the loop.
                            break;

                        case NEED_TASK:
                        {
                            // A task needs to be run, so run it!

                            Runnable task;
                            while ((task=_engine.getDelegatedTask())!=null)
                            {
                                task.run();
                            }

                            // Detect SUN JVM Bug!!!
                            if(initialStatus==HandshakeStatus.NOT_HANDSHAKING &&
                               _engine.getHandshakeStatus()==HandshakeStatus.NEED_UNWRAP && wraps==0)
                            {
                                // This should be NEED_WRAP
                                // The fix simply detects the signature of the bug and then close the connection (fail-fast) so that ff3 will delegate to using SSL instead of TLS.
                                // This is a jvm bug on java1.6 where the SSLEngine expects more data from the initial handshake when the client(ff3-tls) already had given it.
                                // See http://jira.codehaus.org/browse/JETTY-567 for more details
                                if (_debug) __log.warn(_session+" JETTY-567");
                                return -1;
                            }
                            break;
                        }

                        case NEED_WRAP:
                        {
                            checkRenegotiate();
                            // The SSL needs to send some handshake data to the other side,
                            // so let fill become a flush for a little bit.
                            wraps++;
                            needOutBuffer();
                            ByteBuffer out_buffer=_outNIOBuffer.getByteBuffer();
                            synchronized(out_buffer)
                            {
                                try
                                {
                                    // call wrap with empty application buffers, so it can
                                    // generate required handshake messages into _outNIOBuffer
                                    _outNIOBuffer.compact();
                                    int put=_outNIOBuffer.putIndex();
                                    out_buffer.position();
                                    _result=null;
                                    _result=_engine.wrap(__NO_BUFFERS,out_buffer);
                                    if (_debug) __log.debug(_session+" fill wrap "+_result);
                                    switch(_result.getStatus())
                                    {
                                        case BUFFER_OVERFLOW:
                                        case BUFFER_UNDERFLOW:
                                            Log.warn("wrap {}",_result);
                                        case CLOSED:
                                            _closing=true;
                                    }

                                    _outNIOBuffer.setPutIndex(put+_result.bytesProduced());
                                }
                                catch(SSLException e)
                                {
                                    super.close();
                                    throw e;
                                }
                                finally
                                {
                                    out_buffer.position(0);
                                }
                            }

                            // flush the encrypted outNIOBuffer
                            flush();
                            freeOutBuffer();

                            break;
                        }
                    }
                }
            }
            finally
            {
                // reset the Buffers
                buffer.setPutIndex(bbuf.position());
                bbuf.position(0);
            }

            // return the number of unencrypted bytes filled.
            int filled=buffer.length()-size;
            if (filled>0)
                _handshook=true;
            return filled;
        }
    }

    /* ------------------------------------------------------------ */
    @Override
    public int flush(Buffer buffer) throws IOException
    {
        return flush(buffer,null,null);
    }


    /* ------------------------------------------------------------ */
    /*
     */
    @Override
    public int flush(Buffer header, Buffer buffer, Buffer trailer) throws IOException
    {
        int consumed=0;
        int available=header.length();
        if (buffer!=null)
            available+=buffer.length();

        needOutBuffer();
        ByteBuffer out_buffer=_outNIOBuffer.getByteBuffer();
        loop: while (true)
        {
            if (_outNIOBuffer.length()>0)
            {
                flush();
                if (isBufferingOutput())
                    break loop;
            }

            switch(_engine.getHandshakeStatus())
            {
                case FINISHED:
                case NOT_HANDSHAKING:
                    if (_closing || available==0)
                    {
                        if (consumed==0)
                            consumed= -1;
                        break loop;
                    }

                    int c;
                    if (header!=null && header.length()>0)
                    {
                        if (buffer!=null && buffer.length()>0)
                            c=wrap(header,buffer);
                        else
                            c=wrap(header);
                    }
                    else
                        c=wrap(buffer);


                    if (c>0)
                    {
                        _handshook=true;
                        consumed+=c;
                        available-=c;
                    }
                    else if (c<0)
                    {
                        if (consumed==0)
                            consumed=-1;
                        break loop;
                    }

                    break;

                case NEED_UNWRAP:
                    checkRenegotiate();
                    Buffer buf =_buffers.getBuffer(_engine.getSession().getApplicationBufferSize());
                    try
                    {
                        ByteBuffer bbuf = ((NIOBuffer)buf).getByteBuffer();
                        if (!unwrap(bbuf) && _engine.getHandshakeStatus()==HandshakeStatus.NEED_UNWRAP)
                        {
                            break loop;
                        }
                    }
                    finally
                    {
                        _buffers.returnBuffer(buf);
                    }

                    break;

                case NEED_TASK:
                {
                    Runnable task;
                    while ((task=_engine.getDelegatedTask())!=null)
                    {
                        task.run();
                    }
                    break;
                }

                case NEED_WRAP:
                {
                    checkRenegotiate();
                    synchronized(out_buffer)
                    {
                        try
                        {
                            _outNIOBuffer.compact();
                            int put=_outNIOBuffer.putIndex();
                            out_buffer.position();
                            _result=null;
                            _result=_engine.wrap(__NO_BUFFERS,out_buffer);
                            if (_debug) __log.debug(_session+" flush wrap "+_result);
                            switch(_result.getStatus())
                            {
                                case BUFFER_OVERFLOW:
                                case BUFFER_UNDERFLOW:
                                    Log.warn("unwrap {}",_result);
                                case CLOSED:
                                    _closing=true;
                            }
                            _outNIOBuffer.setPutIndex(put+_result.bytesProduced());
                        }
                        catch(SSLException e)
                        {
                            super.close();
                            throw e;
                        }
                        finally
                        {
                            out_buffer.position(0);
                        }
                    }

                    flush();
                    if (isBufferingOutput())
                        break loop;

                    break;
                }
            }
        }

        freeOutBuffer();
        return consumed;
    }

    /* ------------------------------------------------------------ */
    @Override
    public void flush() throws IOException
    {
        if (_outNIOBuffer==null)
            return;

        int len=_outNIOBuffer.length();
        if (isBufferingOutput())
        {
            int flushed=super.flush(_outNIOBuffer);
            if (_debug) __log.debug(_session+" Flushed "+flushed+"/"+len);
            if (isBufferingOutput())
            {
                // Try again after yield.... cheaper than a reschedule.
                Thread.yield();
                flushed=super.flush(_outNIOBuffer);
                if (_debug) __log.debug(_session+" flushed "+flushed+"/"+len);
            }
            else if (_closing && !_engine.isOutboundDone())
            {
                _engine.closeOutbound();
            }
        }
    }

    /* ------------------------------------------------------------ */
    private void checkRenegotiate() throws IOException
    {
        if (_handshook && !_allowRenegotiate && _channel!=null && _channel.isOpen())
        {
            Log.warn("SSL renegotiate denied: "+_channel);
            super.close();
        }
    }

    /* ------------------------------------------------------------ */
    private ByteBuffer extractInputBuffer(Buffer buffer)
    {
        assert buffer instanceof NIOBuffer;
        NIOBuffer nbuf=(NIOBuffer)buffer;
        ByteBuffer bbuf=nbuf.getByteBuffer();
        bbuf.position(buffer.putIndex());
        return bbuf;
    }

    /* ------------------------------------------------------------ */
    /**
     * @return true if progress is made
     */
    private boolean unwrap(ByteBuffer buffer) throws IOException
    {
        needInBuffer();
        ByteBuffer in_buffer=_inNIOBuffer.getByteBuffer();

        if (_inNIOBuffer.hasContent())
            _inNIOBuffer.compact();
        else
            _inNIOBuffer.clear();

        int total_filled=0;
        boolean remoteClosed = false;
        // loop filling as much encrypted data as we can into the buffer
        while (_inNIOBuffer.space()>0 && super.isOpen())
        {
            try
            {
                int filled=super.fill(_inNIOBuffer);
                if (_debug) __log.debug(_session+" unwrap filled "+filled);
                if (filled < 0)
                {
                    __log.info("{} fill() returned -1, _inNIOBuffer {}", _socket, _inNIOBuffer); // TODO: remove this
                    remoteClosed = true;
                }
                // break the loop if no progress is made (we have read everything there is to read)
                if (filled<=0)
                    break;
                total_filled+=filled;
            }
            catch(IOException e)
            {
                if (_inNIOBuffer.length()==0)
                {
                    if (_outNIOBuffer!=null)
                    {
                        _outNIOBuffer.clear();
                        freeOutBuffer();
                    }
                    throw e;
                }
                break;
            }
        }

        // If we have no progress and no data
        if (total_filled==0 && _inNIOBuffer.length()==0)
        {
            if (isOpen())
            {
                if (remoteClosed)
                {
                    try
                    {
                        _engine.closeInbound();
                    }
                    catch (SSLException x)
                    {
                        // It may happen, for example, in case of truncation
                        // attacks, we close so that we do not spin forever.
                        freeOutBuffer();
                        super.close();
                    }
                }
            }
            else
            {
                freeOutBuffer();
                throw new EofException();
            }
            __log.info("{} uwrap() returning false, _inNIOBuffer {}", _socket, _inNIOBuffer); // TODO: remove this
            return false;
        }

        if (remoteClosed)
            __log.info("{} uwrapping, _inNIOBuffer {}", _socket, _inNIOBuffer); // TODO: remove this

        // We have some in data, so try to unwrap it.
        try
        {
            // inBuffer is the NIO buffer inside the _inNIOBuffer,
            // so update its position and limit from the inNIOBuffer.
            in_buffer.position(_inNIOBuffer.getIndex());
            in_buffer.limit(_inNIOBuffer.putIndex());
            _result=null;

            // Do the unwrap
            _result=_engine.unwrap(in_buffer,buffer);
            if (_debug) __log.debug(_session+" unwrap unwrap "+_result);

            // skip the bytes consumed
            _inNIOBuffer.skip(_result.bytesConsumed());
        }
        catch(SSLException e)
        {
            Log.warn(getRemoteAddr()+":"+getRemotePort()+" "+e);
            super.close();
            throw e;
        }
        finally
        {
            // reset the buffer so it can be managed by the _inNIOBuffer again.
            in_buffer.position(0);
            in_buffer.limit(in_buffer.capacity());
            freeInBuffer();
        }

        // handle the unwrap results
        switch(_result.getStatus())
        {
            case BUFFER_OVERFLOW:
                throw new IllegalStateException(_result.toString()+" "+buffer.position()+" "+buffer.limit());

            case BUFFER_UNDERFLOW:
                // Not enough data,
                // If we are closed, we will never get more, so EOF
                // else return and we will be tried again
                // later when more data arriving causes another dispatch.
                if (Log.isDebugEnabled()) Log.debug("unwrap {}",_result);
                if(!isOpen())
                {
                    _inNIOBuffer.clear();
                    if (_outNIOBuffer!=null)
                        _outNIOBuffer.clear();
                    throw new EofException();
                }
                return (total_filled > 0);

            case CLOSED:
                _closing=true;
                // return true is some bytes somewhere were moved about.
                return total_filled>0 ||_result.bytesConsumed()>0 || _result.bytesProduced()>0;
            case OK:
                // return true is some bytes somewhere were moved about.
                return total_filled>0 ||_result.bytesConsumed()>0 || _result.bytesProduced()>0;
            default:
                Log.warn("unwrap "+_result);
                throw new IOException(_result.toString());
        }
    }


    /* ------------------------------------------------------------ */
    private ByteBuffer extractOutputBuffer(Buffer buffer)
    {
        if (buffer.buffer() instanceof NIOBuffer)
            return ((NIOBuffer)buffer.buffer()).getByteBuffer();

        return ByteBuffer.wrap(buffer.array());
    }

    /* ------------------------------------------------------------ */
    private int wrap(final Buffer header, final Buffer buffer) throws IOException
    {
        _gather[0]=extractOutputBuffer(header);

        synchronized(_gather[0])
        {
            _gather[0].position(header.getIndex());
            _gather[0].limit(header.putIndex());

            _gather[1]=extractOutputBuffer(buffer);

            synchronized(_gather[1])
            {
                _gather[1].position(buffer.getIndex());
                _gather[1].limit(buffer.putIndex());

                needOutBuffer();
                ByteBuffer out_buffer=_outNIOBuffer.getByteBuffer();
                synchronized(out_buffer)
                {
                    int consumed=0;
                    try
                    {
                        _outNIOBuffer.clear();
                        out_buffer.position(0);
                        out_buffer.limit(out_buffer.capacity());

                        _result=null;
                        _result=_engine.wrap(_gather,out_buffer);
                        if (_debug) __log.debug(_session+" wrap wrap "+_result);
                        _outNIOBuffer.setGetIndex(0);
                        _outNIOBuffer.setPutIndex(_result.bytesProduced());
                        consumed=_result.bytesConsumed();
                    }
                    catch(SSLException e)
                    {
                        Log.warn(getRemoteAddr()+":"+getRemotePort()+" "+e);
                        super.close();
                        throw e;
                    }
                    finally
                    {
                        out_buffer.position(0);

                        if (consumed>0)
                        {
                            int len=consumed<header.length()?consumed:header.length();
                            header.skip(len);
                            consumed-=len;
                            _gather[0].position(0);
                            _gather[0].limit(_gather[0].capacity());
                        }
                        if (consumed>0)
                        {
                            int len=consumed<buffer.length()?consumed:buffer.length();
                            buffer.skip(len);
                            consumed-=len;
                            _gather[1].position(0);
                            _gather[1].limit(_gather[1].capacity());
                        }
                        assert consumed==0;

                        freeOutBuffer();
                    }
                }
            }
        }


        switch(_result.getStatus())
        {
            case BUFFER_OVERFLOW:
            case BUFFER_UNDERFLOW:
                Log.warn("unwrap {}",_result);

            case OK:
                return _result.bytesConsumed();
            case CLOSED:
                _closing=true;
                return _result.bytesConsumed()>0?_result.bytesConsumed():-1;

            default:
                Log.warn("wrap "+_result);
            throw new IOException(_result.toString());
        }
    }

    /* ------------------------------------------------------------ */
    private int wrap(final Buffer buffer) throws IOException
    {
        _gather[0]=extractOutputBuffer(buffer);
        synchronized(_gather[0])
        {
            ByteBuffer bb;

            _gather[0].position(buffer.getIndex());
            _gather[0].limit(buffer.putIndex());

            int consumed=0;
            needOutBuffer();
            ByteBuffer out_buffer=_outNIOBuffer.getByteBuffer();
            synchronized(out_buffer)
            {
                try
                {
                    _outNIOBuffer.clear();
                    out_buffer.position(0);
                    out_buffer.limit(out_buffer.capacity());
                    _result=null;
                    _result=_engine.wrap(_gather[0],out_buffer);
                    if (_debug) __log.debug(_session+" wrap wrap "+_result);
                    _outNIOBuffer.setGetIndex(0);
                    _outNIOBuffer.setPutIndex(_result.bytesProduced());
                    consumed=_result.bytesConsumed();
                }
                catch(SSLException e)
                {
                    Log.warn(getRemoteAddr()+":"+getRemotePort()+" "+e);
                    super.close();
                    throw e;
                }
                finally
                {
                    out_buffer.position(0);

                    if (consumed>0)
                    {
                        int len=consumed<buffer.length()?consumed:buffer.length();
                        buffer.skip(len);
                        consumed-=len;
                        _gather[0].position(0);
                        _gather[0].limit(_gather[0].capacity());
                    }
                    assert consumed==0;

                    freeOutBuffer();
                }
            }
        }
        switch(_result.getStatus())
        {
            case BUFFER_OVERFLOW:
            case BUFFER_UNDERFLOW:
                Log.warn("unwrap {}",_result);

            case OK:
                return _result.bytesConsumed();
            case CLOSED:
                _closing=true;
                return _result.bytesConsumed()>0?_result.bytesConsumed():-1;

            default:
                Log.warn("wrap "+_result);
            throw new IOException(_result.toString());
        }
    }

    /* ------------------------------------------------------------ */
    @Override
    public boolean isBufferingInput()
    {
        final Buffer in = _inNIOBuffer;
        return in==null?false:_inNIOBuffer.hasContent();
    }

    /* ------------------------------------------------------------ */
    @Override
    public boolean isBufferingOutput()
    {
        final NIOBuffer b=_outNIOBuffer;
        return b==null?false:b.hasContent();
    }

    /* ------------------------------------------------------------ */
    @Override
    public boolean isBufferred()
    {
        return true;
    }

    /* ------------------------------------------------------------ */
    public SSLEngine getSSLEngine()
    {
        return _engine;
    }

    /* ------------------------------------------------------------ */
    @Override
    public void scheduleWrite()
    {
        // only set !writable if we are not waiting for input
        if (!HandshakeStatus.NEED_UNWRAP.equals(_engine.getHandshakeStatus()) || super.isBufferingOutput())
        super.scheduleWrite();
    }

    /* ------------------------------------------------------------ */
    @Override
    public String toString()
    {
        final NIOBuffer i=_inNIOBuffer;
        final NIOBuffer o=_outNIOBuffer;
        return "SSL"+super.toString()+","+_engine.getHandshakeStatus()+", in/out="+
        (i==null?0:_inNIOBuffer.length())+"/"+(o==null?0:o.length())+
        " bi/o="+isBufferingInput()+"/"+isBufferingOutput()+
        " "+_result;
    }
}

Back to the top