blob: f6bf334c347b10791da370887a5c313d16ee1dbb [file] [log] [blame]
Adam Tkac35e6d4c2010-04-23 14:12:18 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 * Copyright (C) 2005 Martin Koegler
3 * Copyright (C) 2010 TigerVNC Team
4 *
5 * This is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This software is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this software; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
18 * USA.
19 */
20
21#ifdef HAVE_CONFIG_H
22#include <config.h>
23#endif
24
25#include <rdr/Exception.h>
26#include <rdr/TLSException.h>
27#include <rdr/TLSInStream.h>
28#include <errno.h>
29
30#ifdef HAVE_GNUTLS
31using namespace rdr;
32
33enum { DEFAULT_BUF_SIZE = 16384 };
34
35ssize_t rdr::gnutls_InStream_pull(gnutls_transport_ptr str, void* data,
36 size_t size)
37{
38 InStream* in= (InStream*) str;
39
40 if (!in->check(1, 1, false)) {
41 errno=EAGAIN;
42 return -1;
43 }
44
45 if (in->getend() - in->getptr() < size)
46 size = in->getend() - in->getptr();
47
48 in->readBytes(data, size);
49
50 return size;
51}
52
53TLSInStream::TLSInStream(InStream* _in, gnutls_session _session)
54 : session(_session), in(_in), bufSize(DEFAULT_BUF_SIZE), offset(0)
55{
56 ptr = end = start = new U8[bufSize];
57}
58
59TLSInStream::~TLSInStream()
60{
61 delete[] start;
62}
63
64int TLSInStream::pos()
65{
66 return offset + ptr - start;
67}
68
69int TLSInStream::overrun(int itemSize, int nItems, bool wait)
70{
71 if (itemSize > bufSize)
72 throw Exception("TLSInStream overrun: max itemSize exceeded");
73
74 if (end - ptr != 0)
75 memmove(start, ptr, end - ptr);
76
77 offset += ptr - start;
78 end -= ptr - start;
79 ptr = start;
80
81 while (end < start + itemSize) {
82 int n = readTLS((U8*) end, start + bufSize - end, wait);
83 if (!wait && n == 0)
84 return 0;
85 end += n;
86 }
87
88 if (itemSize * nItems > end - ptr)
89 nItems = (end - ptr) / itemSize;
90
91 return nItems;
92}
93
94int TLSInStream::readTLS(U8* buf, int len, bool wait)
95{
96 int n;
97
98 n = in->check(1, 1, wait);
99 if (n == 0)
100 return 0;
101
102 n = gnutls_record_recv(session, (void *) buf, len);
103 if (n == GNUTLS_E_INTERRUPTED || n == GNUTLS_E_AGAIN)
104 return 0;
105
106 if (n < 0) throw TLSException("readTLS", n);
107
108 return n;
109}
110
111#endif