blob: 888b455b586ee96581009e0b582825b73f067b40 [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/TLSOutStream.h>
Adam Tkacfab093c2010-08-25 13:52:49 +000028#include <errno.h>
Adam Tkac35e6d4c2010-04-23 14:12:18 +000029
30#ifdef HAVE_GNUTLS
31using namespace rdr;
32
33enum { DEFAULT_BUF_SIZE = 16384 };
34
35ssize_t rdr::gnutls_OutStream_push(gnutls_transport_ptr str, const void* data,
36 size_t size)
37{
38 OutStream* out = (OutStream*) str;
Adam Tkacfab093c2010-08-25 13:52:49 +000039
40 try {
41 out->writeBytes(data, size);
42 out->flush();
43 } catch (Exception& e) {
44 gnutls_transport_set_global_errno(EINVAL);
45 return -1;
46 }
47
Adam Tkac35e6d4c2010-04-23 14:12:18 +000048 return size;
49}
50
51TLSOutStream::TLSOutStream(OutStream* _out, gnutls_session _session)
52 : session(_session), out(_out), bufSize(DEFAULT_BUF_SIZE), offset(0)
53{
54 ptr = start = new U8[bufSize];
55 end = start + bufSize;
56}
57
58TLSOutStream::~TLSOutStream()
59{
60#if 0
61 try {
62// flush();
63 } catch (Exception&) {
64 }
65#endif
66 delete [] start;
67}
68
69int TLSOutStream::length()
70{
71 return offset + ptr - start;
72}
73
74void TLSOutStream::flush()
75{
76 U8* sentUpTo = start;
77 while (sentUpTo < ptr) {
78 int n = writeTLS(sentUpTo, ptr - sentUpTo);
79 sentUpTo += n;
80 offset += n;
81 }
82
83 ptr = start;
84 out->flush();
85}
86
87int TLSOutStream::overrun(int itemSize, int nItems)
88{
89 if (itemSize > bufSize)
90 throw Exception("TLSOutStream overrun: max itemSize exceeded");
91
92 flush();
93
94 if (itemSize * nItems > end - ptr)
95 nItems = (end - ptr) / itemSize;
96
97 return nItems;
98}
99
100int TLSOutStream::writeTLS(const U8* data, int length)
101{
102 int n;
103
104 n = gnutls_record_send(session, data, length);
105 if (n == GNUTLS_E_INTERRUPTED || n == GNUTLS_E_AGAIN)
106 return 0;
107
108 if (n < 0)
109 throw TLSException("writeTLS", n);
110
111 return n;
112}
113
114#endif