1 /* Copyright (C) 2002-2005 RealVNC Ltd.  All Rights Reserved.
2  * Copyright (C) 2005 Martin Koegler
3  * Copyright (C) 2010 TigerVNC Team
4  * Copyright (C) 2011-2019 Brian P. Hinz
5  *
6  * This is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This software is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this software; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
19  * USA.
20  */
21 
22 package com.tigervnc.rdr;
23 
24 import java.nio.ByteBuffer;
25 import java.nio.channels.*;
26 import javax.net.ssl.*;
27 
28 import com.tigervnc.network.*;
29 
30 public class TLSOutStream extends OutStream {
31 
32   static final int defaultBufSize = 16384;
33 
TLSOutStream(OutStream _out, SSLEngineManager _manager)34   public TLSOutStream(OutStream _out, SSLEngineManager _manager) {
35     manager = _manager;
36     out = (FdOutStream)_out;
37     SSLSession session = manager.getSession();
38     bufSize = session.getApplicationBufferSize();
39     b = new byte[bufSize];
40     ptr = offset = start = 0;
41     end = start + bufSize;
42   }
43 
length()44   public int length()
45   {
46     return offset + ptr - start;
47   }
48 
flush()49   public void flush()
50   {
51     int sentUpTo = start;
52     while (sentUpTo < ptr) {
53       int n = writeTLS(b, sentUpTo, ptr - sentUpTo);
54       sentUpTo += n;
55       offset += n;
56     }
57 
58     ptr = start;
59   }
60 
overrun(int itemSize, int nItems)61   protected int overrun(int itemSize, int nItems)
62   {
63     if (itemSize > bufSize)
64       throw new Exception("TLSOutStream overrun: max itemSize exceeded");
65 
66     flush();
67 
68     int nAvail;
69     nAvail = (end - ptr) / itemSize;
70     if (nAvail < nItems)
71       return nAvail;
72 
73     return nItems;
74   }
75 
writeTLS(byte[] data, int dataPtr, int length)76   protected int writeTLS(byte[] data, int dataPtr, int length)
77   {
78     int n = 0;
79 
80     try {
81       n = manager.write(ByteBuffer.wrap(data, dataPtr, length), length);
82     } catch (java.io.IOException e) {
83       throw new Exception(e.getMessage());
84     }
85 
86     return n;
87   }
88 
89   private SSLEngineManager manager;
90   private FdOutStream out;
91   private int start;
92   private int offset;
93   private int bufSize;
94 }
95