blob: 22433a1b74f084904926f80f61196d08ba0b0828 [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 *
3 * This is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This software is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
16 * USA.
17 */
18
Adam Tkac8aee1a82009-09-04 12:08:56 +000019#ifdef HAVE_CONFIG_H
20#include <config.h>
Adam Tkac49e5ce62008-11-14 12:25:34 +000021#endif
22
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000023#include <stdio.h>
24#include <string.h>
25#ifdef _WIN32
26#include <winsock2.h>
27#ifndef _WIN32_WCE
28#include <sys/timeb.h>
29#endif
30#define read(s,b,l) recv(s,(char*)b,l,0)
31#define close closesocket
32#undef errno
33#define errno WSAGetLastError()
Peter Åstrand (astrand)11167e12015-02-05 11:10:32 +010034#include <os/winerrno.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000035#else
36#include <sys/types.h>
37#include <errno.h>
38#include <unistd.h>
39#include <sys/time.h>
40#endif
41
42#ifndef vncmin
43#define vncmin(a,b) (((a) < (b)) ? (a) : (b))
44#endif
45#ifndef vncmax
46#define vncmax(a,b) (((a) > (b)) ? (a) : (b))
47#endif
48
Adam Tkac49e5ce62008-11-14 12:25:34 +000049/* Old systems have select() in sys/time.h */
50#ifdef HAVE_SYS_SELECT_H
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000051#include <sys/select.h>
52#endif
53
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000054#include <rdr/FdInStream.h>
55#include <rdr/Exception.h>
56
57using namespace rdr;
58
59enum { DEFAULT_BUF_SIZE = 8192,
60 MIN_BULK_SIZE = 1024 };
61
62FdInStream::FdInStream(int fd_, int timeoutms_, int bufSize_,
63 bool closeWhenDone_)
64 : fd(fd_), closeWhenDone(closeWhenDone_),
65 timeoutms(timeoutms_), blockCallback(0),
66 timing(false), timeWaitedIn100us(5), timedKbits(0),
67 bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0)
68{
69 ptr = end = start = new U8[bufSize];
70}
71
72FdInStream::FdInStream(int fd_, FdInStreamBlockCallback* blockCallback_,
73 int bufSize_)
74 : fd(fd_), timeoutms(0), blockCallback(blockCallback_),
75 timing(false), timeWaitedIn100us(5), timedKbits(0),
76 bufSize(bufSize_ ? bufSize_ : DEFAULT_BUF_SIZE), offset(0)
77{
78 ptr = end = start = new U8[bufSize];
79}
80
81FdInStream::~FdInStream()
82{
83 delete [] start;
84 if (closeWhenDone) close(fd);
85}
86
87
88void FdInStream::setTimeout(int timeoutms_) {
89 timeoutms = timeoutms_;
90}
91
92void FdInStream::setBlockCallback(FdInStreamBlockCallback* blockCallback_)
93{
94 blockCallback = blockCallback_;
95 timeoutms = 0;
96}
97
98int FdInStream::pos()
99{
100 return offset + ptr - start;
101}
102
103void FdInStream::readBytes(void* data, int length)
104{
105 if (length < MIN_BULK_SIZE) {
106 InStream::readBytes(data, length);
107 return;
108 }
109
110 U8* dataPtr = (U8*)data;
111
112 int n = end - ptr;
113 if (n > length) n = length;
114
115 memcpy(dataPtr, ptr, n);
116 dataPtr += n;
117 length -= n;
118 ptr += n;
119
120 while (length > 0) {
121 n = readWithTimeoutOrCallback(dataPtr, length);
122 dataPtr += n;
123 length -= n;
124 offset += n;
125 }
126}
127
128
129int FdInStream::overrun(int itemSize, int nItems, bool wait)
130{
131 if (itemSize > bufSize)
132 throw Exception("FdInStream overrun: max itemSize exceeded");
133
134 if (end - ptr != 0)
135 memmove(start, ptr, end - ptr);
136
137 offset += ptr - start;
138 end -= ptr - start;
139 ptr = start;
140
141 int bytes_to_read;
142 while (end < start + itemSize) {
143 bytes_to_read = start + bufSize - end;
144 if (!timing) {
145 // When not timing, we must be careful not to read too much
146 // extra data into the buffer. Otherwise, the line speed
147 // estimation might stay at zero for a long time: All reads
148 // during timing=1 can be satisfied without calling
149 // readWithTimeoutOrCallback. However, reading only 1 or 2 bytes
150 // bytes is ineffecient.
151 bytes_to_read = vncmin(bytes_to_read, vncmax(itemSize*nItems, 8));
152 }
153 int n = readWithTimeoutOrCallback((U8*)end, bytes_to_read, wait);
154 if (n == 0) return 0;
155 end += n;
156 }
157
158 if (itemSize * nItems > end - ptr)
159 nItems = (end - ptr) / itemSize;
160
161 return nItems;
162}
163
164#ifdef _WIN32
165static void gettimeofday(struct timeval* tv, void*)
166{
167 LARGE_INTEGER counts, countsPerSec;
168 static double usecPerCount = 0.0;
169
170 if (QueryPerformanceCounter(&counts)) {
171 if (usecPerCount == 0.0) {
172 QueryPerformanceFrequency(&countsPerSec);
173 usecPerCount = 1000000.0 / countsPerSec.QuadPart;
174 }
175
176 LONGLONG usecs = (LONGLONG)(counts.QuadPart * usecPerCount);
177 tv->tv_usec = (long)(usecs % 1000000);
178 tv->tv_sec = (long)(usecs / 1000000);
179
180 } else {
181#ifndef _WIN32_WCE
182 struct timeb tb;
183 ftime(&tb);
184 tv->tv_sec = tb.time;
185 tv->tv_usec = tb.millitm * 1000;
186#else
187 throw SystemException("QueryPerformanceCounter", GetLastError());
188#endif
189 }
190}
191#endif
192
193//
194// readWithTimeoutOrCallback() reads up to the given length in bytes from the
195// file descriptor into a buffer. If the wait argument is false, then zero is
196// returned if no bytes can be read without blocking. Otherwise if a
197// blockCallback is set, it will be called (repeatedly) instead of blocking.
198// If alternatively there is a timeout set and that timeout expires, it throws
199// a TimedOut exception. Otherwise it returns the number of bytes read. It
200// never attempts to read() unless select() indicates that the fd is readable -
201// this means it can be used on an fd which has been set non-blocking. It also
202// has to cope with the annoying possibility of both select() and read()
203// returning EINTR.
204//
205
206int FdInStream::readWithTimeoutOrCallback(void* buf, int len, bool wait)
207{
208 struct timeval before, after;
209 if (timing)
210 gettimeofday(&before, 0);
211
212 int n;
213 while (true) {
214 do {
215 fd_set fds;
216 struct timeval tv;
217 struct timeval* tvp = &tv;
218
219 if (!wait) {
220 tv.tv_sec = tv.tv_usec = 0;
221 } else if (timeoutms != -1) {
222 tv.tv_sec = timeoutms / 1000;
223 tv.tv_usec = (timeoutms % 1000) * 1000;
224 } else {
225 tvp = 0;
226 }
227
228 FD_ZERO(&fds);
229 FD_SET(fd, &fds);
230 n = select(fd+1, &fds, 0, 0, tvp);
231 } while (n < 0 && errno == EINTR);
232
233 if (n > 0) break;
234 if (n < 0) throw SystemException("select",errno);
235 if (!wait) return 0;
236 if (!blockCallback) throw TimedOut();
237
238 blockCallback->blockCallback();
239 }
240
241 do {
242 n = ::read(fd, buf, len);
243 } while (n < 0 && errno == EINTR);
244
245 if (n < 0) throw SystemException("read",errno);
246 if (n == 0) throw EndOfStream();
247
248 if (timing) {
249 gettimeofday(&after, 0);
250// fprintf(stderr,"%d.%06d\n",(after.tv_sec - before.tv_sec),
251// (after.tv_usec - before.tv_usec));
252 int newTimeWaited = ((after.tv_sec - before.tv_sec) * 10000 +
253 (after.tv_usec - before.tv_usec) / 100);
254 int newKbits = n * 8 / 1000;
255
256// if (newTimeWaited == 0) {
257// fprintf(stderr,"new kbps infinite t %d k %d\n",
258// newTimeWaited, newKbits);
259// } else {
260// fprintf(stderr,"new kbps %d t %d k %d\n",
261// newKbits * 10000 / newTimeWaited, newTimeWaited, newKbits);
262// }
263
264 // limit rate to between 10kbit/s and 40Mbit/s
265
266 if (newTimeWaited > newKbits*1000) newTimeWaited = newKbits*1000;
267 if (newTimeWaited < newKbits/4) newTimeWaited = newKbits/4;
268
269 timeWaitedIn100us += newTimeWaited;
270 timedKbits += newKbits;
271 }
272
273 return n;
274}
275
276void FdInStream::startTiming()
277{
278 timing = true;
279
280 // Carry over up to 1s worth of previous rate for smoothing.
281
282 if (timeWaitedIn100us > 10000) {
283 timedKbits = timedKbits * 10000 / timeWaitedIn100us;
284 timeWaitedIn100us = 10000;
285 }
286}
287
288void FdInStream::stopTiming()
289{
290 timing = false;
291 if (timeWaitedIn100us < timedKbits/2)
292 timeWaitedIn100us = timedKbits/2; // upper limit 20Mbit/s
293}
294
295unsigned int FdInStream::kbitsPerSecond()
296{
297 // The following calculation will overflow 32-bit arithmetic if we have
298 // received more than about 50Mbytes (400Mbits) since we started timing, so
299 // it should be OK for a single RFB update.
300
301 return timedKbits * 10000 / timeWaitedIn100us;
302}