blob: 0e97a78471ec2215bef45465a7dce01bedac9fbc [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossmancef3cf72016-11-25 10:06:34 +01002 * Copyright 2009-2016 Pierre Ossman for Cendio AB
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00003 *
4 * This is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This software is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this software; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17 * USA.
18 */
19
Pierre Ossman1b478e52011-11-15 12:08:30 +000020// Debug output on what the congestion control is up to
21#undef CONGESTION_DEBUG
22
23#include <sys/time.h>
24
25#ifdef CONGESTION_DEBUG
26#include <sys/socket.h>
27#include <netinet/in.h>
28#include <netinet/tcp.h>
29#endif
30
Pierre Ossmana830bec2011-11-08 12:12:02 +000031#include <network/TcpSocket.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000032#include <rfb/VNCSConnectionST.h>
33#include <rfb/LogWriter.h>
Adam Tkac5a0caed2010-04-23 13:58:10 +000034#include <rfb/Security.h>
Pierre Ossmanc5e25602009-03-20 12:59:05 +000035#include <rfb/screenTypes.h>
Pierre Ossman2c764942011-11-14 15:54:30 +000036#include <rfb/fenceTypes.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010037#include <rfb/ledStates.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000038#include <rfb/ServerCore.h>
39#include <rfb/ComparingUpdateTracker.h>
40#include <rfb/KeyRemapper.h>
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +010041#include <rfb/Encoder.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010042#define XK_LATIN1
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000043#define XK_MISCELLANY
44#define XK_XKB_KEYS
45#include <rfb/keysymdef.h>
46
47using namespace rfb;
48
49static LogWriter vlog("VNCSConnST");
50
Pierre Ossman1b478e52011-11-15 12:08:30 +000051// This window should get us going fairly fast on a decent bandwidth network.
52// If it's too high, it will rapidly be reduced and stay low.
53static const unsigned INITIAL_WINDOW = 16384;
54
55// TCP's minimal window is 3*MSS. But since we don't know the MSS, we
klemens0536d092017-01-28 20:56:56 +010056// make a guess at 4 KiB (it's probably a bit higher).
Pierre Ossman1b478e52011-11-15 12:08:30 +000057static const unsigned MINIMUM_WINDOW = 4096;
58
59// The current default maximum window for Linux (4 MiB). Should be a good
60// limit for now...
61static const unsigned MAXIMUM_WINDOW = 4194304;
62
63struct RTTInfo {
64 struct timeval tv;
65 int offset;
66 unsigned inFlight;
67};
68
Pierre Ossman71ca8d52017-09-15 11:03:12 +020069static Cursor emptyCursor(0, 0, Point(0, 0), NULL);
70
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000071VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
72 bool reverse)
Pierre Ossman7069bdd2015-02-06 14:41:58 +010073 : sock(s), reverseConnection(reverse),
Pierre Ossman36304752017-10-04 16:21:57 +020074 inProcessMessages(false),
Pierre Ossmanb8b1e962012-07-20 10:47:00 +000075 pendingSyncFence(false), syncFence(false), fenceFlags(0),
76 fenceDataLen(0), fenceData(NULL),
Pierre Ossmanb1cd6ca2015-03-03 16:37:43 +010077 baseRTT(-1), congWindow(0), ackedOffset(0), sentOffset(0),
78 minRTT(-1), seenCongestion(false),
79 pingCounter(0), congestionTimer(this),
Pierre Ossman0c9bd4b2014-07-09 16:44:11 +020080 server(server_), updates(false),
Pierre Ossman671d2ef2015-06-09 16:09:06 +020081 updateRenderedCursor(false), removeRenderedCursor(false),
Pierre Ossmana40ab202016-04-29 15:35:56 +020082 continuousUpdates(false), encodeManager(this), pointerEventTime(0),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000083 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000084{
85 setStreams(&sock->inStream(), &sock->outStream());
86 peerEndpoint.buf = sock->getPeerEndpoint();
87 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
88
89 // Configure the socket
90 setSocketTimeouts();
91 lastEventTime = time(0);
92
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000093 server->clients.push_front(this);
94}
95
96
97VNCSConnectionST::~VNCSConnectionST()
98{
99 // If we reach here then VNCServerST is deleting us!
100 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
101 peerEndpoint.buf,
102 (closeReason.buf) ? closeReason.buf : "");
103
104 // Release any keys the client still had pressed
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200105 while (!pressedKeys.empty()) {
106 rdr::U32 keysym, keycode;
107
108 keysym = pressedKeys.begin()->second;
109 keycode = pressedKeys.begin()->first;
110 pressedKeys.erase(pressedKeys.begin());
111
112 vlog.debug("Releasing key 0x%x / 0x%x on client disconnect",
113 keysym, keycode);
114 server->desktop->keyEvent(keysym, keycode, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200115 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200116
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000117 if (server->pointerClient == this)
118 server->pointerClient = 0;
119
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000120 // Remove this client from the server
121 server->clients.remove(this);
122
Pierre Ossman2c764942011-11-14 15:54:30 +0000123 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000124}
125
126
127// Methods called from VNCServerST
128
129bool VNCSConnectionST::init()
130{
131 try {
132 initialiseProtocol();
133 } catch (rdr::Exception& e) {
134 close(e.str());
135 return false;
136 }
137 return true;
138}
139
140void VNCSConnectionST::close(const char* reason)
141{
142 // Log the reason for the close
143 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000144 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000145 else
146 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
147
148 if (authenticated()) {
149 server->lastDisconnectTime = time(0);
150 }
151
152 // Just shutdown the socket and mark our state as closing. Eventually the
153 // calling code will call VNCServerST's removeSocket() method causing us to
154 // be deleted.
155 sock->shutdown();
156 setState(RFBSTATE_CLOSING);
157}
158
159
160void VNCSConnectionST::processMessages()
161{
162 if (state() == RFBSTATE_CLOSING) return;
163 try {
164 // - Now set appropriate socket timeouts and process data
165 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000166
167 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000168
Pierre Ossmana830bec2011-11-08 12:12:02 +0000169 // Get the underlying TCP layer to build large packets if we send
170 // multiple small responses.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +0200171 sock->cork(true);
Pierre Ossmana830bec2011-11-08 12:12:02 +0000172
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000173 while (getInStream()->checkNoWait(1)) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000174 if (pendingSyncFence) {
175 syncFence = true;
176 pendingSyncFence = false;
177 }
178
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000179 processMsg();
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000180
Pierre Ossman2c764942011-11-14 15:54:30 +0000181 if (syncFence) {
182 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
183 syncFence = false;
184 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000185 }
186
Pierre Ossmana830bec2011-11-08 12:12:02 +0000187 // Flush out everything in case we go idle after this.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +0200188 sock->cork(false);
Pierre Ossmana830bec2011-11-08 12:12:02 +0000189
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000190 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000191
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000192 // If there were anything requiring an update, try to send it here.
193 // We wait until now with this to aggregate responses and to give
194 // higher priority to user actions such as keyboard and pointer events.
195 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000196 } catch (rdr::EndOfStream&) {
197 close("Clean disconnection");
198 } catch (rdr::Exception &e) {
199 close(e.str());
200 }
201}
202
Pierre Ossmand408ca52016-04-29 14:26:05 +0200203void VNCSConnectionST::flushSocket()
204{
205 if (state() == RFBSTATE_CLOSING) return;
206 try {
207 setSocketTimeouts();
208 sock->outStream().flush();
Pierre Ossmana40ab202016-04-29 15:35:56 +0200209 // Flushing the socket might release an update that was previously
210 // delayed because of congestion.
211 if (sock->outStream().bufferUsage() == 0)
212 writeFramebufferUpdate();
Pierre Ossmand408ca52016-04-29 14:26:05 +0200213 } catch (rdr::Exception &e) {
214 close(e.str());
215 }
216}
217
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000218void VNCSConnectionST::pixelBufferChange()
219{
220 try {
221 if (!authenticated()) return;
222 if (cp.width && cp.height && (server->pb->width() != cp.width ||
223 server->pb->height() != cp.height))
224 {
225 // We need to clip the next update to the new size, but also add any
226 // extra bits if it's bigger. If we wanted to do this exactly, something
227 // like the code below would do it, but at the moment we just update the
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200228 // entire new size. However, we do need to clip the damagedCursorRegion
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000229 // because that might be added to updates in writeFramebufferUpdate().
230
231 //updates.intersect(server->pb->getRect());
232 //
233 //if (server->pb->width() > cp.width)
234 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
235 // server->pb->height()));
236 //if (server->pb->height() > cp.height)
237 // updates.add_changed(Rect(0, cp.height, cp.width,
238 // server->pb->height()));
239
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200240 damagedCursorRegion.assign_intersect(server->pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000241
242 cp.width = server->pb->width();
243 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000244 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000245 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000246 // We should only send EDS to client asking for both
247 if (!writer()->writeExtendedDesktopSize()) {
248 if (!writer()->writeSetDesktopSize()) {
249 close("Client does not support desktop resize");
250 return;
251 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000252 }
253 }
254 }
255 // Just update the whole screen at the moment because we're too lazy to
256 // work out what's actually changed.
257 updates.clear();
258 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000259 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000260 } catch(rdr::Exception &e) {
261 close(e.str());
262 }
263}
264
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000265void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000266{
267 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000268 writeFramebufferUpdate();
269 } catch(rdr::Exception &e) {
270 close(e.str());
271 }
272}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000273
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000274void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
275{
276 try {
277 screenLayoutChange(reason);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000278 } catch(rdr::Exception &e) {
279 close(e.str());
280 }
281}
282
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000283void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000284{
285 try {
286 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
287 } catch(rdr::Exception& e) {
288 close(e.str());
289 }
290}
291
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000292void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000293{
294 try {
295 if (!(accessRights & AccessCutText)) return;
296 if (!rfb::Server::sendCutText) return;
297 if (state() == RFBSTATE_NORMAL)
298 writer()->writeServerCutText(str, len);
299 } catch(rdr::Exception& e) {
300 close(e.str());
301 }
302}
303
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000304
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000305void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000306{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000307 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000308 setDesktopName(name);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000309 } catch(rdr::Exception& e) {
310 close(e.str());
311 }
312}
313
314
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000315void VNCSConnectionST::setCursorOrClose()
316{
317 try {
318 setCursor();
319 } catch(rdr::Exception& e) {
320 close(e.str());
321 }
322}
323
324
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100325void VNCSConnectionST::setLEDStateOrClose(unsigned int state)
326{
327 try {
328 setLEDState(state);
329 } catch(rdr::Exception& e) {
330 close(e.str());
331 }
332}
333
334
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000335int VNCSConnectionST::checkIdleTimeout()
336{
337 int idleTimeout = rfb::Server::idleTimeout;
338 if (idleTimeout == 0) return 0;
339 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
340 idleTimeout = 15; // minimum of 15 seconds while authenticating
341 time_t now = time(0);
342 if (now < lastEventTime) {
343 // Someone must have set the time backwards. Set lastEventTime so that the
344 // idleTimeout will count from now.
345 vlog.info("Time has gone backwards - resetting idle timeout");
346 lastEventTime = now;
347 }
348 int timeLeft = lastEventTime + idleTimeout - now;
349 if (timeLeft < -60) {
350 // Our callback is over a minute late - someone must have set the time
351 // forwards. Set lastEventTime so that the idleTimeout will count from
352 // now.
353 vlog.info("Time has gone forwards - resetting idle timeout");
354 lastEventTime = now;
355 return secsToMillis(idleTimeout);
356 }
357 if (timeLeft <= 0) {
358 close("Idle timeout");
359 return 0;
360 }
361 return secsToMillis(timeLeft);
362}
363
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000364
365bool VNCSConnectionST::getComparerState()
366{
367 // We interpret a low compression level as an indication that the client
368 // wants to prioritise CPU usage over bandwidth, and hence disable the
369 // comparing update tracker.
370 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
371}
372
373
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000374// renderedCursorChange() is called whenever the server-side rendered cursor
375// changes shape or position. It ensures that the next update will clean up
376// the old rendered cursor and if necessary draw the new rendered cursor.
377
378void VNCSConnectionST::renderedCursorChange()
379{
380 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200381 // Are we switching between client-side and server-side cursor?
Pierre Ossman330ca422017-11-06 13:15:55 +0100382 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
383 if (hasRenderedCursor != needRenderedCursor())
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200384 setCursorOrClose();
Pierre Ossman330ca422017-11-06 13:15:55 +0100385 if (hasRenderedCursor)
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000386 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000387 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200388 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000389 writeFramebufferUpdateOrClose();
390 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000391}
392
393// needRenderedCursor() returns true if this client needs the server-side
394// rendered cursor. This may be because it does not support local cursor or
395// because the current cursor position has not been set by this client.
396// Unfortunately we can't know for sure when the current cursor position has
397// been set by this client. We guess that this is the case when the current
398// cursor position is the same as the last pointer event from this client, or
399// if it is a very short time since this client's last pointer event (up to a
400// second). [ Ideally we should do finer-grained timing here and make the time
401// configurable, but I don't think it's that important. ]
402
403bool VNCSConnectionST::needRenderedCursor()
404{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100405 if (state() != RFBSTATE_NORMAL)
406 return false;
407
Pierre Ossman324043e2017-08-16 16:26:11 +0200408 if (!cp.supportsLocalCursorWithAlpha &&
409 !cp.supportsLocalCursor && !cp.supportsLocalXCursor)
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100410 return true;
411 if (!server->cursorPos.equals(pointerEventPos) &&
412 (time(0) - pointerEventTime) > 0)
413 return true;
414
415 return false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000416}
417
418
419void VNCSConnectionST::approveConnectionOrClose(bool accept,
420 const char* reason)
421{
422 try {
423 approveConnection(accept, reason);
424 } catch (rdr::Exception& e) {
425 close(e.str());
426 }
427}
428
429
430
431// -=- Callbacks from SConnection
432
433void VNCSConnectionST::authSuccess()
434{
435 lastEventTime = time(0);
436
437 server->startDesktop();
438
439 // - Set the connection parameters appropriately
440 cp.width = server->pb->width();
441 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000442 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000443 cp.setName(server->getName());
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100444 cp.setLEDState(server->ledState);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000445
446 // - Set the default pixel format
447 cp.setPF(server->pb->getPF());
448 char buffer[256];
449 cp.pf().print(buffer, 256);
450 vlog.info("Server default pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000451
452 // - Mark the entire display as "dirty"
453 updates.add_changed(server->pb->getRect());
454 startTime = time(0);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000455
456 // - Bootstrap the congestion control
457 ackedOffset = sock->outStream().length();
458 congWindow = INITIAL_WINDOW;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000459}
460
461void VNCSConnectionST::queryConnection(const char* userName)
462{
463 // - Authentication succeeded - clear from blacklist
464 CharArray name; name.buf = sock->getPeerAddress();
465 server->blHosts->clearBlackmark(name.buf);
466
467 // - Special case to provide a more useful error message
468 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
469 server->authClientCount() > 0) {
470 approveConnection(false, "The server is already in use");
471 return;
472 }
473
474 // - Does the client have the right to bypass the query?
475 if (reverseConnection ||
476 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
477 (accessRights & AccessNoQuery))
478 {
479 approveConnection(true);
480 return;
481 }
482
483 // - Get the server to display an Accept/Reject dialog, if required
484 // If a dialog is displayed, the result will be PENDING, and the
485 // server will call approveConnection at a later time
486 CharArray reason;
487 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
488 &reason.buf);
Pierre Ossman36304752017-10-04 16:21:57 +0200489 if (qr == VNCServerST::PENDING)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000490 return;
491
492 // - If server returns ACCEPT/REJECT then pass result to SConnection
493 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
494}
495
496void VNCSConnectionST::clientInit(bool shared)
497{
498 lastEventTime = time(0);
499 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100500 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000501 if (rfb::Server::neverShared) shared = false;
502 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100503 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000504 // - Close all the other connected clients
505 vlog.debug("non-shared connection - closing clients");
506 server->closeClients("Non-shared connection requested", getSock());
507 } else {
508 // - Refuse this connection if there are existing clients, in addition to
509 // this one
510 if (server->authClientCount() > 1) {
511 close("Server is already in use");
512 return;
513 }
514 }
515 }
516 SConnection::clientInit(shared);
517}
518
519void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
520{
521 SConnection::setPixelFormat(pf);
522 char buffer[256];
523 pf.print(buffer, 256);
524 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000525 setCursor();
526}
527
528void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
529{
530 pointerEventTime = lastEventTime = time(0);
531 server->lastUserInputTime = lastEventTime;
532 if (!(accessRights & AccessPtrEvents)) return;
533 if (!rfb::Server::acceptPointerEvents) return;
534 if (!server->pointerClient || server->pointerClient == this) {
535 pointerEventPos = pos;
536 if (buttonMask)
537 server->pointerClient = this;
538 else
539 server->pointerClient = 0;
540 server->desktop->pointerEvent(pointerEventPos, buttonMask);
541 }
542}
543
544
545class VNCSConnectionSTShiftPresser {
546public:
547 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
548 : desktop(desktop_), pressed(false) {}
549 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200550 if (pressed) {
551 vlog.debug("Releasing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200552 desktop->keyEvent(XK_Shift_L, 0, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200553 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000554 }
555 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200556 vlog.debug("Pressing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200557 desktop->keyEvent(XK_Shift_L, 0, true);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000558 pressed = true;
559 }
560 SDesktop* desktop;
561 bool pressed;
562};
563
564// keyEvent() - record in the pressedKeys which keys were pressed. Allow
565// multiple down events (for autorepeat), but only allow a single up event.
Pierre Ossman5ae28212017-05-16 14:30:38 +0200566void VNCSConnectionST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200567 rdr::U32 lookup;
568
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000569 lastEventTime = time(0);
570 server->lastUserInputTime = lastEventTime;
571 if (!(accessRights & AccessKeyEvents)) return;
572 if (!rfb::Server::acceptKeyEvents) return;
573
Pierre Ossman9a153b02015-08-31 10:01:14 +0200574 if (down)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200575 vlog.debug("Key pressed: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200576 else
Pierre Ossman5ae28212017-05-16 14:30:38 +0200577 vlog.debug("Key released: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200578
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000579 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200580 if (server->keyRemapper) {
581 rdr::U32 newkey;
Pierre Ossman5ae28212017-05-16 14:30:38 +0200582 newkey = server->keyRemapper->remapKey(keysym);
583 if (newkey != keysym) {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200584 vlog.debug("Key remapped to 0x%x", newkey);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200585 keysym = newkey;
Pierre Ossman9a153b02015-08-31 10:01:14 +0200586 }
587 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000588
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100589 // Avoid lock keys if we don't know the server state
590 if ((server->ledState == ledUnknown) &&
Pierre Ossman5ae28212017-05-16 14:30:38 +0200591 ((keysym == XK_Caps_Lock) ||
592 (keysym == XK_Num_Lock) ||
593 (keysym == XK_Scroll_Lock))) {
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100594 vlog.debug("Ignoring lock key (e.g. caps lock)");
595 return;
596 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100597
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100598 // Lock key heuristics
599 // (only for clients that do not support the LED state extension)
600 if (!cp.supportsLEDState) {
601 // Always ignore ScrollLock as we don't have a heuristic
602 // for that
Pierre Ossman5ae28212017-05-16 14:30:38 +0200603 if (keysym == XK_Scroll_Lock) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100604 vlog.debug("Ignoring lock key (e.g. caps lock)");
605 return;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100606 }
607
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100608 if (down && (server->ledState != ledUnknown)) {
609 // CapsLock synchronisation heuristic
610 // (this assumes standard interaction between CapsLock the Shift
611 // keys and normal characters)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200612 if (((keysym >= XK_A) && (keysym <= XK_Z)) ||
613 ((keysym >= XK_a) && (keysym <= XK_z))) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100614 bool uppercase, shift, lock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100615
Pierre Ossman5ae28212017-05-16 14:30:38 +0200616 uppercase = (keysym >= XK_A) && (keysym <= XK_Z);
Pierre Ossman851e6802017-09-12 16:44:44 +0200617 shift = isShiftPressed();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100618 lock = server->ledState & ledCapsLock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100619
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100620 if (lock == (uppercase == shift)) {
621 vlog.debug("Inserting fake CapsLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200622 server->desktop->keyEvent(XK_Caps_Lock, 0, true);
623 server->desktop->keyEvent(XK_Caps_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100624 }
625 }
626
627 // NumLock synchronisation heuristic
628 // (this is more cautious because of the differences between Unix,
629 // Windows and macOS)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200630 if (((keysym >= XK_KP_Home) && (keysym <= XK_KP_Delete)) ||
631 ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
632 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal)) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100633 bool number, shift, lock;
634
Pierre Ossman5ae28212017-05-16 14:30:38 +0200635 number = ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
636 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal);
Pierre Ossman851e6802017-09-12 16:44:44 +0200637 shift = isShiftPressed();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100638 lock = server->ledState & ledNumLock;
639
640 if (shift) {
641 // We don't know the appropriate NumLock state for when Shift
642 // is pressed as it could be one of:
643 //
644 // a) A Unix client where Shift negates NumLock
645 //
646 // b) A Windows client where Shift only cancels NumLock
647 //
648 // c) A macOS client where Shift doesn't have any effect
649 //
650 } else if (lock == (number == shift)) {
651 vlog.debug("Inserting fake NumLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200652 server->desktop->keyEvent(XK_Num_Lock, 0, true);
653 server->desktop->keyEvent(XK_Num_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100654 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100655 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000656 }
657 }
658
659 // Turn ISO_Left_Tab into shifted Tab.
660 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200661 if (keysym == XK_ISO_Left_Tab) {
Pierre Ossman851e6802017-09-12 16:44:44 +0200662 if (!isShiftPressed())
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000663 shiftPresser.press();
Pierre Ossman5ae28212017-05-16 14:30:38 +0200664 keysym = XK_Tab;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000665 }
666
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200667 // We need to be able to track keys, so generate a fake index when we
668 // aren't given a keycode
669 if (keycode == 0)
670 lookup = 0x80000000 | keysym;
671 else
672 lookup = keycode;
673
674 // We force the same keysym for an already down key for the
675 // sake of sanity
676 if (pressedKeys.find(lookup) != pressedKeys.end())
677 keysym = pressedKeys[lookup];
678
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000679 if (down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200680 pressedKeys[lookup] = keysym;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000681 } else {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200682 if (!pressedKeys.erase(lookup))
Pierre Ossman5ae28212017-05-16 14:30:38 +0200683 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000684 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200685
Pierre Ossman5ae28212017-05-16 14:30:38 +0200686 server->desktop->keyEvent(keysym, keycode, down);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000687}
688
689void VNCSConnectionST::clientCutText(const char* str, int len)
690{
691 if (!(accessRights & AccessCutText)) return;
692 if (!rfb::Server::acceptCutText) return;
693 server->desktop->clientCutText(str, len);
694}
695
696void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
697{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000698 Rect safeRect;
699
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000700 if (!(accessRights & AccessView)) return;
701
702 SConnection::framebufferUpdateRequest(r, incremental);
703
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000704 // Check that the client isn't sending crappy requests
705 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
706 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
707 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000708 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
709 } else {
710 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000711 }
712
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000713 // Just update the requested region.
714 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000715 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000716 if (!incremental || !continuousUpdates)
717 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000718
719 if (!incremental) {
720 // Non-incremental update - treat as if area requested has changed
721 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000722
723 // And send the screen layout to the client (which, unlike the
724 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000725 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000726
727 // We do not send a DesktopSize since it only contains the
728 // framebuffer size (which the client already should know) and
729 // because some clients don't handle extra DesktopSize events
730 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000731 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000732}
733
Pierre Ossman34bb0612009-03-21 21:16:14 +0000734void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
735 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000736{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000737 unsigned int result;
738
Michal Srbb318b8f2014-11-24 13:18:28 +0200739 if (!(accessRights & AccessSetDesktopSize)) return;
740 if (!rfb::Server::acceptSetDesktopSize) return;
741
Pierre Ossman04e62db2009-03-23 16:57:07 +0000742 // Don't bother the desktop with an invalid configuration
743 if (!layout.validate(fb_width, fb_height)) {
744 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
745 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000746 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000747 return;
748 }
749
750 // FIXME: the desktop will call back to VNCServerST and an extra set
751 // of ExtendedDesktopSize messages will be sent. This is okay
752 // protocol-wise, but unnecessary.
753 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
754
Pierre Ossman04e62db2009-03-23 16:57:07 +0000755 writer()->writeExtendedDesktopSize(reasonClient, result,
756 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000757
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000758 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000759 if (result == resultSuccess) {
760 if (server->screenLayout != layout)
761 throw Exception("Desktop configured a different screen layout than requested");
762 server->notifyScreenLayoutChange(this);
763 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000764
765 // but always send back a reply to the requesting client
766 // (do this last as it might throw an exception on socket errors)
767 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000768}
769
Pierre Ossman2c764942011-11-14 15:54:30 +0000770void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
771{
772 if (flags & fenceFlagRequest) {
773 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000774 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000775
776 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
777 fenceDataLen = len;
778 delete [] fenceData;
Michal Srbf3afa242017-03-27 19:02:15 +0300779 fenceData = NULL;
Pierre Ossman2c764942011-11-14 15:54:30 +0000780 if (len > 0) {
781 fenceData = new char[len];
782 memcpy(fenceData, data, len);
783 }
784
785 return;
786 }
787
788 // We handle everything synchronously so we trivially honor these modes
789 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
790
791 writer()->writeFence(flags, len, data);
792 return;
793 }
794
Pierre Ossman1b478e52011-11-15 12:08:30 +0000795 struct RTTInfo rttInfo;
796
Pierre Ossman2c764942011-11-14 15:54:30 +0000797 switch (len) {
798 case 0:
799 // Initial dummy fence;
800 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000801 case sizeof(struct RTTInfo):
802 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
803 handleRTTPong(rttInfo);
804 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000805 default:
806 vlog.error("Fence response of unexpected size received");
807 }
808}
809
Pierre Ossman1b478e52011-11-15 12:08:30 +0000810void VNCSConnectionST::enableContinuousUpdates(bool enable,
811 int x, int y, int w, int h)
812{
813 Rect rect;
814
815 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
816 throw Exception("Client tried to enable continuous updates when not allowed");
817
818 continuousUpdates = enable;
819
820 rect.setXYWH(x, y, w, h);
821 cuRegion.reset(rect);
822
823 if (enable) {
824 requested.clear();
825 writeFramebufferUpdate();
826 } else {
827 writer()->writeEndOfContinuousUpdates();
828 }
829}
830
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000831// supportsLocalCursor() is called whenever the status of
832// cp.supportsLocalCursor has changed. If the client does now support local
833// cursor, we make sure that the old server-side rendered cursor is cleaned up
834// and the cursor is sent to the client.
835
836void VNCSConnectionST::supportsLocalCursor()
837{
Pierre Ossman324043e2017-08-16 16:26:11 +0200838 if (cp.supportsLocalCursorWithAlpha ||
839 cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200840 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000841 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000842 setCursor();
843 }
844}
845
Pierre Ossman2c764942011-11-14 15:54:30 +0000846void VNCSConnectionST::supportsFence()
847{
848 writer()->writeFence(fenceFlagRequest, 0, NULL);
849}
850
Pierre Ossman1b478e52011-11-15 12:08:30 +0000851void VNCSConnectionST::supportsContinuousUpdates()
852{
853 // We refuse to use continuous updates if we cannot monitor the buffer
854 // usage using fences.
855 if (!cp.supportsFence)
856 return;
857
858 writer()->writeEndOfContinuousUpdates();
859}
860
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100861void VNCSConnectionST::supportsLEDState()
862{
863 writer()->writeLEDState();
864}
865
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000866
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000867bool VNCSConnectionST::handleTimeout(Timer* t)
868{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000869 try {
Pierre Ossmana40ab202016-04-29 15:35:56 +0200870 if (t == &congestionTimer)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000871 updateCongestion();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000872 } catch (rdr::Exception& e) {
873 close(e.str());
874 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000875
876 return false;
877}
878
Pierre Ossman851e6802017-09-12 16:44:44 +0200879bool VNCSConnectionST::isShiftPressed()
880{
881 std::map<rdr::U32, rdr::U32>::const_iterator iter;
882
883 for (iter = pressedKeys.begin(); iter != pressedKeys.end(); ++iter) {
884 if (iter->second == XK_Shift_L)
885 return true;
886 if (iter->second == XK_Shift_R)
887 return true;
888 }
889
890 return false;
891}
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000892
Pierre Ossman1b478e52011-11-15 12:08:30 +0000893void VNCSConnectionST::writeRTTPing()
894{
895 struct RTTInfo rttInfo;
896
897 if (!cp.supportsFence)
898 return;
899
900 memset(&rttInfo, 0, sizeof(struct RTTInfo));
901
902 gettimeofday(&rttInfo.tv, NULL);
903 rttInfo.offset = sock->outStream().length();
904 rttInfo.inFlight = rttInfo.offset - ackedOffset;
905
906 // We need to make sure any old update are already processed by the
907 // time we get the response back. This allows us to reliably throttle
908 // back on client overload, as well as network overload.
909 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
910 sizeof(struct RTTInfo), (const char*)&rttInfo);
911
912 pingCounter++;
913
914 sentOffset = rttInfo.offset;
915
916 // Let some data flow before we adjust the settings
917 if (!congestionTimer.isStarted())
918 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
919}
920
921void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
922{
923 unsigned rtt, delay;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000924
925 pingCounter--;
926
927 rtt = msSince(&rttInfo.tv);
928 if (rtt < 1)
929 rtt = 1;
930
931 ackedOffset = rttInfo.offset;
932
933 // Try to estimate wire latency by tracking lowest seen latency
934 if (rtt < baseRTT)
935 baseRTT = rtt;
936
937 if (rttInfo.inFlight > congWindow) {
938 seenCongestion = true;
939
940 // Estimate added delay because of overtaxed buffers
941 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
942
943 if (delay < rtt)
944 rtt -= delay;
945 else
946 rtt = 1;
947
948 // If we underestimate the congestion window, then we'll get a latency
949 // that's less than the wire latency, which will confuse other portions
950 // of the code.
951 if (rtt < baseRTT)
952 rtt = baseRTT;
953 }
954
955 // We only keep track of the minimum latency seen (for a given interval)
klemens0536d092017-01-28 20:56:56 +0100956 // on the basis that we want to avoid continuous buffer issue, but don't
Pierre Ossman1b478e52011-11-15 12:08:30 +0000957 // mind (or even approve of) bursts.
958 if (rtt < minRTT)
959 minRTT = rtt;
960}
961
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000962bool VNCSConnectionST::isCongested()
963{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000964 int offset;
965
966 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200967 sock->outStream().flush();
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000968 if (sock->outStream().bufferUsage() > 0)
969 return true;
970
Pierre Ossman1b478e52011-11-15 12:08:30 +0000971 if (!cp.supportsFence)
972 return false;
973
974 // Idle for too long? (and no data on the wire)
975 //
976 // FIXME: This should really just be one baseRTT, but we're getting
977 // problems with triggering the idle timeout on each update.
978 // Maybe we need to use a moving average for the wire latency
979 // instead of baseRTT.
980 if ((sentOffset == ackedOffset) &&
981 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
982
983#ifdef CONGESTION_DEBUG
984 if (congWindow > INITIAL_WINDOW)
985 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
986 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
987#endif
988
989 // Close congestion window and allow a transfer
990 // FIXME: Reset baseRTT like Linux Vegas?
991 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
992
993 return false;
994 }
995
996 offset = sock->outStream().length();
997
998 // FIXME: Should we compensate for non-update data?
999 // (i.e. use sentOffset instead of offset)
1000 if ((offset - ackedOffset) < congWindow)
1001 return false;
1002
1003 // If we just have one outstanding "ping", that means the client has
1004 // started receiving our update. In order to not regress compared to
1005 // before we had congestion avoidance, we allow another update here.
1006 // This could further clog up the tubes, but congestion control isn't
1007 // really working properly right now anyway as the wire would otherwise
1008 // be idle for at least RTT/2.
1009 if (pingCounter == 1)
1010 return false;
1011
1012 return true;
1013}
1014
1015
1016void VNCSConnectionST::updateCongestion()
1017{
1018 unsigned diff;
1019
1020 if (!seenCongestion)
1021 return;
1022
1023 diff = minRTT - baseRTT;
1024
1025 if (diff > __rfbmin(100, baseRTT)) {
1026 // Way too fast
1027 congWindow = congWindow * baseRTT / minRTT;
1028 } else if (diff > __rfbmin(50, baseRTT/2)) {
1029 // Slightly too fast
1030 congWindow -= 4096;
1031 } else if (diff < 5) {
1032 // Way too slow
1033 congWindow += 8192;
1034 } else if (diff < 25) {
1035 // Too slow
1036 congWindow += 4096;
1037 }
1038
1039 if (congWindow < MINIMUM_WINDOW)
1040 congWindow = MINIMUM_WINDOW;
1041 if (congWindow > MAXIMUM_WINDOW)
1042 congWindow = MAXIMUM_WINDOW;
1043
1044#ifdef CONGESTION_DEBUG
1045 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
1046 minRTT, baseRTT, congWindow / 1024,
1047 congWindow * 8.0 / baseRTT / 1000.0);
1048
1049#ifdef TCP_INFO
1050 struct tcp_info tcp_info;
1051 socklen_t tcp_info_length;
1052
1053 tcp_info_length = sizeof(tcp_info);
1054 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
1055 (void *)&tcp_info, &tcp_info_length) == 0) {
1056 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
1057 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
1058 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
1059 }
1060#endif
1061
1062#endif
1063
1064 minRTT = -1;
1065 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001066}
1067
1068
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001069void VNCSConnectionST::writeFramebufferUpdate()
1070{
Pierre Ossman2c764942011-11-14 15:54:30 +00001071 // We're in the middle of processing a command that's supposed to be
1072 // synchronised. Allowing an update to slip out right now might violate
1073 // that synchronisation.
1074 if (syncFence)
1075 return;
1076
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001077 // We try to aggregate responses, so don't send out anything whilst we
1078 // still have incoming messages. processMessages() will give us another
1079 // chance to run once things are idle.
1080 if (inProcessMessages)
1081 return;
1082
Pierre Ossman1b478e52011-11-15 12:08:30 +00001083 if (state() != RFBSTATE_NORMAL)
1084 return;
1085 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +00001086 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +00001087
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001088 // Check that we actually have some space on the link and retry in a
1089 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +02001090 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001091 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001092
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001093 // Updates often consists of many small writes, and in continuous
1094 // mode, we will also have small fence messages around the update. We
1095 // need to aggregate these in order to not clog up TCP's congestion
1096 // window.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +02001097 sock->cork(true);
Pierre Ossman36dadf82011-11-15 12:11:32 +00001098
Pierre Ossmane9962f72009-04-23 12:31:42 +00001099 // First take care of any updates that cannot contain framebuffer data
1100 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001101 writeNoDataUpdate();
1102
1103 // Then real data (if possible)
1104 writeDataUpdate();
1105
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +02001106 sock->cork(false);
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001107}
1108
1109void VNCSConnectionST::writeNoDataUpdate()
1110{
1111 if (!writer()->needNoDataUpdate())
1112 return;
1113
1114 writer()->writeNoDataUpdate();
1115
1116 // Make sure no data update is sent until next request
1117 requested.clear();
1118}
1119
1120void VNCSConnectionST::writeDataUpdate()
1121{
1122 Region req;
1123 UpdateInfo ui;
1124 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +01001125 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001126
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001127 updates.enable_copyrect(cp.useCopyRect);
1128
Pierre Ossman6e49e952016-10-07 15:59:38 +02001129 // See if we are allowed to send anything right now (the framebuffer
1130 // might have changed in ways we haven't yet been informed of).
Pierre Ossmanbbf955e2011-11-08 12:44:10 +00001131 if (!server->checkUpdate())
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001132 return;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +00001133
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001134 // See what the client has requested (if anything)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001135 if (continuousUpdates)
1136 req = cuRegion.union_(requested);
1137 else
1138 req = requested;
1139
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001140 if (req.is_empty())
1141 return;
1142
1143 // Get the lists of updates. Prior to exporting the data to the `ui' object,
1144 // getUpdateInfo() will normalize the `updates' object such way that its
1145 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +00001146 updates.getUpdateInfo(&ui, req);
1147 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001148
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001149 // If the previous position of the rendered cursor overlaps the source of the
1150 // copy, then when the copy happens the corresponding rectangle in the
1151 // destination will be wrong, so add it to the changed region.
1152
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001153 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
1154 Region bogusCopiedCursor;
1155
1156 bogusCopiedCursor.copyFrom(damagedCursorRegion);
1157 bogusCopiedCursor.translate(ui.copy_delta);
1158 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001159 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001160 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001161 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001162 }
1163 }
1164
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001165 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001166 // the changed region.
1167
1168 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001169 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001170 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001171 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001172 removeRenderedCursor = false;
1173 }
1174
1175 // Return if there is nothing to send the client.
1176
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001177 if (updates.is_empty() && !writer()->needFakeUpdate() && !updateRenderedCursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001178 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001179
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001180 // The `updates' object could change, make sure we have valid update info.
1181
1182 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001183 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001184
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001185 // If the client needs a server-side rendered cursor, work out the cursor
1186 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1187 // with the update region, we need to draw the rendered cursor regardless of
1188 // whether it has changed.
1189
Pierre Ossman24684e52016-12-05 16:58:19 +01001190 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001191 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001192 Rect renderedCursorRect;
1193
Pierre Ossman24684e52016-12-05 16:58:19 +01001194 cursor = server->getRenderedCursor();
1195
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001196 renderedCursorRect
Pierre Ossman24684e52016-12-05 16:58:19 +01001197 = cursor->getEffectiveRect().intersect(req.get_bounding_rect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001198
1199 if (renderedCursorRect.is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001200 cursor = NULL;
1201 } else if (!updateRenderedCursor &&
1202 ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001203 .intersect(renderedCursorRect).is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001204 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001205 }
1206
Pierre Ossman5c037202016-12-05 17:00:35 +01001207 if (cursor) {
1208 updates.subtract(renderedCursorRect);
1209 updates.getUpdateInfo(&ui, req);
1210 }
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001211
1212 damagedCursorRegion.assign_union(renderedCursorRect);
1213 updateRenderedCursor = false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001214 }
1215
Pierre Ossman24684e52016-12-05 16:58:19 +01001216 if (ui.is_empty() && !writer()->needFakeUpdate() && !cursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001217 return;
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001218
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001219 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001220
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001221 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001222
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001223 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001224
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001225 // The request might be for just part of the screen, so we cannot
1226 // just clear the entire update tracker.
1227 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001228
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001229 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001230}
1231
1232
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001233void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1234{
1235 if (!authenticated())
1236 return;
1237
1238 cp.screenLayout = server->screenLayout;
1239
1240 if (state() != RFBSTATE_NORMAL)
1241 return;
1242
1243 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1244 cp.screenLayout);
1245 writeFramebufferUpdate();
1246}
1247
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001248
1249// setCursor() is called whenever the cursor has changed shape or pixel format.
1250// If the client supports local cursor then it will arrange for the cursor to
1251// be sent to the client.
1252
1253void VNCSConnectionST::setCursor()
1254{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001255 if (state() != RFBSTATE_NORMAL)
1256 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001257
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001258 // We need to blank out the client's cursor or there will be two
1259 if (needRenderedCursor())
1260 cp.setCursor(emptyCursor);
1261 else
1262 cp.setCursor(*server->cursor);
Pierre Ossman126e5642014-02-13 14:40:25 +01001263
Pierre Ossman8053c8e2017-02-21 12:59:04 +01001264 if (!writer()->writeSetCursorWithAlpha()) {
1265 if (!writer()->writeSetCursor()) {
1266 if (!writer()->writeSetXCursor()) {
1267 // No client support
1268 return;
1269 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001270 }
1271 }
1272
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001273 writeFramebufferUpdate();
1274}
1275
1276void VNCSConnectionST::setDesktopName(const char *name)
1277{
1278 cp.setName(name);
1279
1280 if (state() != RFBSTATE_NORMAL)
1281 return;
1282
1283 if (!writer()->writeSetDesktopName()) {
1284 fprintf(stderr, "Client does not support desktop rename\n");
1285 return;
1286 }
1287
1288 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001289}
1290
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001291void VNCSConnectionST::setLEDState(unsigned int ledstate)
1292{
1293 if (state() != RFBSTATE_NORMAL)
1294 return;
1295
1296 cp.setLEDState(ledstate);
1297
1298 if (!writer()->writeLEDState()) {
1299 // No client support
1300 return;
1301 }
1302
1303 writeFramebufferUpdate();
1304}
1305
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001306void VNCSConnectionST::setSocketTimeouts()
1307{
1308 int timeoutms = rfb::Server::clientWaitTimeMillis;
1309 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1310 if (timeoutms == 0)
1311 timeoutms = -1;
1312 sock->inStream().setTimeout(timeoutms);
1313 sock->outStream().setTimeout(timeoutms);
1314}
1315
1316char* VNCSConnectionST::getStartTime()
1317{
1318 char* result = ctime(&startTime);
1319 result[24] = '\0';
1320 return result;
1321}
1322
1323void VNCSConnectionST::setStatus(int status)
1324{
1325 switch (status) {
1326 case 0:
1327 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1328 break;
1329 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001330 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001331 break;
1332 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001333 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001334 break;
1335 }
1336 framebufferUpdateRequest(server->pb->getRect(), false);
1337}
1338int VNCSConnectionST::getStatus()
1339{
1340 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1341 return 0;
1342 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1343 return 1;
1344 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1345 return 2;
1346 return 4;
1347}
1348