blob: 6a3e1c7de2f97c504e2791046168c9976943ac7c [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 Ossman25db44a2017-11-16 16:40:44 +010083 clientHasCursor(false),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000084 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000085{
86 setStreams(&sock->inStream(), &sock->outStream());
87 peerEndpoint.buf = sock->getPeerEndpoint();
88 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
89
90 // Configure the socket
91 setSocketTimeouts();
92 lastEventTime = time(0);
93
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000094 server->clients.push_front(this);
95}
96
97
98VNCSConnectionST::~VNCSConnectionST()
99{
100 // If we reach here then VNCServerST is deleting us!
101 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
102 peerEndpoint.buf,
103 (closeReason.buf) ? closeReason.buf : "");
104
105 // Release any keys the client still had pressed
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200106 while (!pressedKeys.empty()) {
107 rdr::U32 keysym, keycode;
108
109 keysym = pressedKeys.begin()->second;
110 keycode = pressedKeys.begin()->first;
111 pressedKeys.erase(pressedKeys.begin());
112
113 vlog.debug("Releasing key 0x%x / 0x%x on client disconnect",
114 keysym, keycode);
115 server->desktop->keyEvent(keysym, keycode, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200116 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200117
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000118 if (server->pointerClient == this)
119 server->pointerClient = 0;
120
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000121 // Remove this client from the server
122 server->clients.remove(this);
123
Pierre Ossman2c764942011-11-14 15:54:30 +0000124 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000125}
126
127
128// Methods called from VNCServerST
129
130bool VNCSConnectionST::init()
131{
132 try {
133 initialiseProtocol();
134 } catch (rdr::Exception& e) {
135 close(e.str());
136 return false;
137 }
138 return true;
139}
140
141void VNCSConnectionST::close(const char* reason)
142{
143 // Log the reason for the close
144 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000145 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000146 else
147 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
148
149 if (authenticated()) {
150 server->lastDisconnectTime = time(0);
151 }
152
153 // Just shutdown the socket and mark our state as closing. Eventually the
154 // calling code will call VNCServerST's removeSocket() method causing us to
155 // be deleted.
156 sock->shutdown();
157 setState(RFBSTATE_CLOSING);
158}
159
160
161void VNCSConnectionST::processMessages()
162{
163 if (state() == RFBSTATE_CLOSING) return;
164 try {
165 // - Now set appropriate socket timeouts and process data
166 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000167
168 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000169
Pierre Ossmana830bec2011-11-08 12:12:02 +0000170 // Get the underlying TCP layer to build large packets if we send
171 // multiple small responses.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +0200172 sock->cork(true);
Pierre Ossmana830bec2011-11-08 12:12:02 +0000173
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000174 while (getInStream()->checkNoWait(1)) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000175 if (pendingSyncFence) {
176 syncFence = true;
177 pendingSyncFence = false;
178 }
179
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000180 processMsg();
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000181
Pierre Ossman2c764942011-11-14 15:54:30 +0000182 if (syncFence) {
183 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
184 syncFence = false;
185 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000186 }
187
Pierre Ossmana830bec2011-11-08 12:12:02 +0000188 // Flush out everything in case we go idle after this.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +0200189 sock->cork(false);
Pierre Ossmana830bec2011-11-08 12:12:02 +0000190
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000191 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000192
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000193 // If there were anything requiring an update, try to send it here.
194 // We wait until now with this to aggregate responses and to give
195 // higher priority to user actions such as keyboard and pointer events.
196 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000197 } catch (rdr::EndOfStream&) {
198 close("Clean disconnection");
199 } catch (rdr::Exception &e) {
200 close(e.str());
201 }
202}
203
Pierre Ossmand408ca52016-04-29 14:26:05 +0200204void VNCSConnectionST::flushSocket()
205{
206 if (state() == RFBSTATE_CLOSING) return;
207 try {
208 setSocketTimeouts();
209 sock->outStream().flush();
Pierre Ossmana40ab202016-04-29 15:35:56 +0200210 // Flushing the socket might release an update that was previously
211 // delayed because of congestion.
212 if (sock->outStream().bufferUsage() == 0)
213 writeFramebufferUpdate();
Pierre Ossmand408ca52016-04-29 14:26:05 +0200214 } catch (rdr::Exception &e) {
215 close(e.str());
216 }
217}
218
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000219void VNCSConnectionST::pixelBufferChange()
220{
221 try {
222 if (!authenticated()) return;
223 if (cp.width && cp.height && (server->pb->width() != cp.width ||
224 server->pb->height() != cp.height))
225 {
226 // We need to clip the next update to the new size, but also add any
227 // extra bits if it's bigger. If we wanted to do this exactly, something
228 // like the code below would do it, but at the moment we just update the
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200229 // entire new size. However, we do need to clip the damagedCursorRegion
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000230 // because that might be added to updates in writeFramebufferUpdate().
231
232 //updates.intersect(server->pb->getRect());
233 //
234 //if (server->pb->width() > cp.width)
235 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
236 // server->pb->height()));
237 //if (server->pb->height() > cp.height)
238 // updates.add_changed(Rect(0, cp.height, cp.width,
239 // server->pb->height()));
240
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200241 damagedCursorRegion.assign_intersect(server->pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000242
243 cp.width = server->pb->width();
244 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000245 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000246 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000247 // We should only send EDS to client asking for both
248 if (!writer()->writeExtendedDesktopSize()) {
249 if (!writer()->writeSetDesktopSize()) {
250 close("Client does not support desktop resize");
251 return;
252 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000253 }
254 }
255 }
256 // Just update the whole screen at the moment because we're too lazy to
257 // work out what's actually changed.
258 updates.clear();
259 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000260 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000261 } catch(rdr::Exception &e) {
262 close(e.str());
263 }
264}
265
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000266void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000267{
268 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000269 writeFramebufferUpdate();
270 } catch(rdr::Exception &e) {
271 close(e.str());
272 }
273}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000274
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000275void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
276{
277 try {
278 screenLayoutChange(reason);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000279 } catch(rdr::Exception &e) {
280 close(e.str());
281 }
282}
283
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000284void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000285{
286 try {
287 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
288 } catch(rdr::Exception& e) {
289 close(e.str());
290 }
291}
292
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000293void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000294{
295 try {
296 if (!(accessRights & AccessCutText)) return;
297 if (!rfb::Server::sendCutText) return;
298 if (state() == RFBSTATE_NORMAL)
299 writer()->writeServerCutText(str, len);
300 } catch(rdr::Exception& e) {
301 close(e.str());
302 }
303}
304
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000305
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000306void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000307{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000308 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000309 setDesktopName(name);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000310 } catch(rdr::Exception& e) {
311 close(e.str());
312 }
313}
314
315
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000316void VNCSConnectionST::setCursorOrClose()
317{
318 try {
319 setCursor();
320 } catch(rdr::Exception& e) {
321 close(e.str());
322 }
323}
324
325
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100326void VNCSConnectionST::setLEDStateOrClose(unsigned int state)
327{
328 try {
329 setLEDState(state);
330 } catch(rdr::Exception& e) {
331 close(e.str());
332 }
333}
334
335
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000336int VNCSConnectionST::checkIdleTimeout()
337{
338 int idleTimeout = rfb::Server::idleTimeout;
339 if (idleTimeout == 0) return 0;
340 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
341 idleTimeout = 15; // minimum of 15 seconds while authenticating
342 time_t now = time(0);
343 if (now < lastEventTime) {
344 // Someone must have set the time backwards. Set lastEventTime so that the
345 // idleTimeout will count from now.
346 vlog.info("Time has gone backwards - resetting idle timeout");
347 lastEventTime = now;
348 }
349 int timeLeft = lastEventTime + idleTimeout - now;
350 if (timeLeft < -60) {
351 // Our callback is over a minute late - someone must have set the time
352 // forwards. Set lastEventTime so that the idleTimeout will count from
353 // now.
354 vlog.info("Time has gone forwards - resetting idle timeout");
355 lastEventTime = now;
356 return secsToMillis(idleTimeout);
357 }
358 if (timeLeft <= 0) {
359 close("Idle timeout");
360 return 0;
361 }
362 return secsToMillis(timeLeft);
363}
364
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000365
366bool VNCSConnectionST::getComparerState()
367{
368 // We interpret a low compression level as an indication that the client
369 // wants to prioritise CPU usage over bandwidth, and hence disable the
370 // comparing update tracker.
371 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
372}
373
374
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000375// renderedCursorChange() is called whenever the server-side rendered cursor
376// changes shape or position. It ensures that the next update will clean up
377// the old rendered cursor and if necessary draw the new rendered cursor.
378
379void VNCSConnectionST::renderedCursorChange()
380{
381 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200382 // Are we switching between client-side and server-side cursor?
Pierre Ossman25db44a2017-11-16 16:40:44 +0100383 if (clientHasCursor == needRenderedCursor())
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200384 setCursorOrClose();
Pierre Ossman25db44a2017-11-16 16:40:44 +0100385 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
Pierre Ossman330ca422017-11-06 13:15:55 +0100386 if (hasRenderedCursor)
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000387 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000388 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200389 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000390 writeFramebufferUpdateOrClose();
391 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000392}
393
394// needRenderedCursor() returns true if this client needs the server-side
395// rendered cursor. This may be because it does not support local cursor or
396// because the current cursor position has not been set by this client.
397// Unfortunately we can't know for sure when the current cursor position has
398// been set by this client. We guess that this is the case when the current
399// cursor position is the same as the last pointer event from this client, or
400// if it is a very short time since this client's last pointer event (up to a
401// second). [ Ideally we should do finer-grained timing here and make the time
402// configurable, but I don't think it's that important. ]
403
404bool VNCSConnectionST::needRenderedCursor()
405{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100406 if (state() != RFBSTATE_NORMAL)
407 return false;
408
Pierre Ossman324043e2017-08-16 16:26:11 +0200409 if (!cp.supportsLocalCursorWithAlpha &&
410 !cp.supportsLocalCursor && !cp.supportsLocalXCursor)
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100411 return true;
412 if (!server->cursorPos.equals(pointerEventPos) &&
413 (time(0) - pointerEventTime) > 0)
414 return true;
415
416 return false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000417}
418
419
420void VNCSConnectionST::approveConnectionOrClose(bool accept,
421 const char* reason)
422{
423 try {
424 approveConnection(accept, reason);
425 } catch (rdr::Exception& e) {
426 close(e.str());
427 }
428}
429
430
431
432// -=- Callbacks from SConnection
433
434void VNCSConnectionST::authSuccess()
435{
436 lastEventTime = time(0);
437
438 server->startDesktop();
439
440 // - Set the connection parameters appropriately
441 cp.width = server->pb->width();
442 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000443 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000444 cp.setName(server->getName());
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100445 cp.setLEDState(server->ledState);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000446
447 // - Set the default pixel format
448 cp.setPF(server->pb->getPF());
449 char buffer[256];
450 cp.pf().print(buffer, 256);
451 vlog.info("Server default pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000452
453 // - Mark the entire display as "dirty"
454 updates.add_changed(server->pb->getRect());
455 startTime = time(0);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000456
457 // - Bootstrap the congestion control
458 ackedOffset = sock->outStream().length();
459 congWindow = INITIAL_WINDOW;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000460}
461
462void VNCSConnectionST::queryConnection(const char* userName)
463{
464 // - Authentication succeeded - clear from blacklist
465 CharArray name; name.buf = sock->getPeerAddress();
466 server->blHosts->clearBlackmark(name.buf);
467
468 // - Special case to provide a more useful error message
469 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
470 server->authClientCount() > 0) {
471 approveConnection(false, "The server is already in use");
472 return;
473 }
474
475 // - Does the client have the right to bypass the query?
476 if (reverseConnection ||
477 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
478 (accessRights & AccessNoQuery))
479 {
480 approveConnection(true);
481 return;
482 }
483
484 // - Get the server to display an Accept/Reject dialog, if required
485 // If a dialog is displayed, the result will be PENDING, and the
486 // server will call approveConnection at a later time
487 CharArray reason;
488 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
489 &reason.buf);
Pierre Ossman36304752017-10-04 16:21:57 +0200490 if (qr == VNCServerST::PENDING)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000491 return;
492
493 // - If server returns ACCEPT/REJECT then pass result to SConnection
494 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
495}
496
497void VNCSConnectionST::clientInit(bool shared)
498{
499 lastEventTime = time(0);
500 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100501 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000502 if (rfb::Server::neverShared) shared = false;
503 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100504 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000505 // - Close all the other connected clients
506 vlog.debug("non-shared connection - closing clients");
507 server->closeClients("Non-shared connection requested", getSock());
508 } else {
509 // - Refuse this connection if there are existing clients, in addition to
510 // this one
511 if (server->authClientCount() > 1) {
512 close("Server is already in use");
513 return;
514 }
515 }
516 }
517 SConnection::clientInit(shared);
518}
519
520void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
521{
522 SConnection::setPixelFormat(pf);
523 char buffer[256];
524 pf.print(buffer, 256);
525 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000526 setCursor();
527}
528
529void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
530{
531 pointerEventTime = lastEventTime = time(0);
532 server->lastUserInputTime = lastEventTime;
533 if (!(accessRights & AccessPtrEvents)) return;
534 if (!rfb::Server::acceptPointerEvents) return;
535 if (!server->pointerClient || server->pointerClient == this) {
536 pointerEventPos = pos;
537 if (buttonMask)
538 server->pointerClient = this;
539 else
540 server->pointerClient = 0;
541 server->desktop->pointerEvent(pointerEventPos, buttonMask);
542 }
543}
544
545
546class VNCSConnectionSTShiftPresser {
547public:
548 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
549 : desktop(desktop_), pressed(false) {}
550 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200551 if (pressed) {
552 vlog.debug("Releasing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200553 desktop->keyEvent(XK_Shift_L, 0, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200554 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000555 }
556 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200557 vlog.debug("Pressing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200558 desktop->keyEvent(XK_Shift_L, 0, true);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000559 pressed = true;
560 }
561 SDesktop* desktop;
562 bool pressed;
563};
564
565// keyEvent() - record in the pressedKeys which keys were pressed. Allow
566// multiple down events (for autorepeat), but only allow a single up event.
Pierre Ossman5ae28212017-05-16 14:30:38 +0200567void VNCSConnectionST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200568 rdr::U32 lookup;
569
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000570 lastEventTime = time(0);
571 server->lastUserInputTime = lastEventTime;
572 if (!(accessRights & AccessKeyEvents)) return;
573 if (!rfb::Server::acceptKeyEvents) return;
574
Pierre Ossman9a153b02015-08-31 10:01:14 +0200575 if (down)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200576 vlog.debug("Key pressed: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200577 else
Pierre Ossman5ae28212017-05-16 14:30:38 +0200578 vlog.debug("Key released: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200579
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000580 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200581 if (server->keyRemapper) {
582 rdr::U32 newkey;
Pierre Ossman5ae28212017-05-16 14:30:38 +0200583 newkey = server->keyRemapper->remapKey(keysym);
584 if (newkey != keysym) {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200585 vlog.debug("Key remapped to 0x%x", newkey);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200586 keysym = newkey;
Pierre Ossman9a153b02015-08-31 10:01:14 +0200587 }
588 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000589
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100590 // Avoid lock keys if we don't know the server state
591 if ((server->ledState == ledUnknown) &&
Pierre Ossman5ae28212017-05-16 14:30:38 +0200592 ((keysym == XK_Caps_Lock) ||
593 (keysym == XK_Num_Lock) ||
594 (keysym == XK_Scroll_Lock))) {
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100595 vlog.debug("Ignoring lock key (e.g. caps lock)");
596 return;
597 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100598
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100599 // Lock key heuristics
600 // (only for clients that do not support the LED state extension)
601 if (!cp.supportsLEDState) {
602 // Always ignore ScrollLock as we don't have a heuristic
603 // for that
Pierre Ossman5ae28212017-05-16 14:30:38 +0200604 if (keysym == XK_Scroll_Lock) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100605 vlog.debug("Ignoring lock key (e.g. caps lock)");
606 return;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100607 }
608
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100609 if (down && (server->ledState != ledUnknown)) {
610 // CapsLock synchronisation heuristic
611 // (this assumes standard interaction between CapsLock the Shift
612 // keys and normal characters)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200613 if (((keysym >= XK_A) && (keysym <= XK_Z)) ||
614 ((keysym >= XK_a) && (keysym <= XK_z))) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100615 bool uppercase, shift, lock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100616
Pierre Ossman5ae28212017-05-16 14:30:38 +0200617 uppercase = (keysym >= XK_A) && (keysym <= XK_Z);
Pierre Ossman851e6802017-09-12 16:44:44 +0200618 shift = isShiftPressed();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100619 lock = server->ledState & ledCapsLock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100620
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100621 if (lock == (uppercase == shift)) {
622 vlog.debug("Inserting fake CapsLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200623 server->desktop->keyEvent(XK_Caps_Lock, 0, true);
624 server->desktop->keyEvent(XK_Caps_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100625 }
626 }
627
628 // NumLock synchronisation heuristic
629 // (this is more cautious because of the differences between Unix,
630 // Windows and macOS)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200631 if (((keysym >= XK_KP_Home) && (keysym <= XK_KP_Delete)) ||
632 ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
633 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal)) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100634 bool number, shift, lock;
635
Pierre Ossman5ae28212017-05-16 14:30:38 +0200636 number = ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
637 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal);
Pierre Ossman851e6802017-09-12 16:44:44 +0200638 shift = isShiftPressed();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100639 lock = server->ledState & ledNumLock;
640
641 if (shift) {
642 // We don't know the appropriate NumLock state for when Shift
643 // is pressed as it could be one of:
644 //
645 // a) A Unix client where Shift negates NumLock
646 //
647 // b) A Windows client where Shift only cancels NumLock
648 //
649 // c) A macOS client where Shift doesn't have any effect
650 //
651 } else if (lock == (number == shift)) {
652 vlog.debug("Inserting fake NumLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200653 server->desktop->keyEvent(XK_Num_Lock, 0, true);
654 server->desktop->keyEvent(XK_Num_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100655 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100656 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000657 }
658 }
659
660 // Turn ISO_Left_Tab into shifted Tab.
661 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200662 if (keysym == XK_ISO_Left_Tab) {
Pierre Ossman851e6802017-09-12 16:44:44 +0200663 if (!isShiftPressed())
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000664 shiftPresser.press();
Pierre Ossman5ae28212017-05-16 14:30:38 +0200665 keysym = XK_Tab;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000666 }
667
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200668 // We need to be able to track keys, so generate a fake index when we
669 // aren't given a keycode
670 if (keycode == 0)
671 lookup = 0x80000000 | keysym;
672 else
673 lookup = keycode;
674
675 // We force the same keysym for an already down key for the
676 // sake of sanity
677 if (pressedKeys.find(lookup) != pressedKeys.end())
678 keysym = pressedKeys[lookup];
679
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000680 if (down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200681 pressedKeys[lookup] = keysym;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000682 } else {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200683 if (!pressedKeys.erase(lookup))
Pierre Ossman5ae28212017-05-16 14:30:38 +0200684 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000685 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200686
Pierre Ossman5ae28212017-05-16 14:30:38 +0200687 server->desktop->keyEvent(keysym, keycode, down);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000688}
689
690void VNCSConnectionST::clientCutText(const char* str, int len)
691{
692 if (!(accessRights & AccessCutText)) return;
693 if (!rfb::Server::acceptCutText) return;
694 server->desktop->clientCutText(str, len);
695}
696
697void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
698{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000699 Rect safeRect;
700
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000701 if (!(accessRights & AccessView)) return;
702
703 SConnection::framebufferUpdateRequest(r, incremental);
704
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000705 // Check that the client isn't sending crappy requests
706 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
707 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
708 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000709 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
710 } else {
711 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000712 }
713
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000714 // Just update the requested region.
715 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000716 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000717 if (!incremental || !continuousUpdates)
718 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000719
720 if (!incremental) {
721 // Non-incremental update - treat as if area requested has changed
722 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000723
724 // And send the screen layout to the client (which, unlike the
725 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000726 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000727
728 // We do not send a DesktopSize since it only contains the
729 // framebuffer size (which the client already should know) and
730 // because some clients don't handle extra DesktopSize events
731 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000732 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000733}
734
Pierre Ossman34bb0612009-03-21 21:16:14 +0000735void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
736 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000737{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000738 unsigned int result;
739
Michal Srbb318b8f2014-11-24 13:18:28 +0200740 if (!(accessRights & AccessSetDesktopSize)) return;
741 if (!rfb::Server::acceptSetDesktopSize) return;
742
Pierre Ossman04e62db2009-03-23 16:57:07 +0000743 // Don't bother the desktop with an invalid configuration
744 if (!layout.validate(fb_width, fb_height)) {
745 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
746 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000747 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000748 return;
749 }
750
751 // FIXME: the desktop will call back to VNCServerST and an extra set
752 // of ExtendedDesktopSize messages will be sent. This is okay
753 // protocol-wise, but unnecessary.
754 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
755
Pierre Ossman04e62db2009-03-23 16:57:07 +0000756 writer()->writeExtendedDesktopSize(reasonClient, result,
757 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000758
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000759 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000760 if (result == resultSuccess) {
761 if (server->screenLayout != layout)
762 throw Exception("Desktop configured a different screen layout than requested");
763 server->notifyScreenLayoutChange(this);
764 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000765
766 // but always send back a reply to the requesting client
767 // (do this last as it might throw an exception on socket errors)
768 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000769}
770
Pierre Ossman2c764942011-11-14 15:54:30 +0000771void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
772{
773 if (flags & fenceFlagRequest) {
774 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000775 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000776
777 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
778 fenceDataLen = len;
779 delete [] fenceData;
Michal Srbf3afa242017-03-27 19:02:15 +0300780 fenceData = NULL;
Pierre Ossman2c764942011-11-14 15:54:30 +0000781 if (len > 0) {
782 fenceData = new char[len];
783 memcpy(fenceData, data, len);
784 }
785
786 return;
787 }
788
789 // We handle everything synchronously so we trivially honor these modes
790 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
791
792 writer()->writeFence(flags, len, data);
793 return;
794 }
795
Pierre Ossman1b478e52011-11-15 12:08:30 +0000796 struct RTTInfo rttInfo;
797
Pierre Ossman2c764942011-11-14 15:54:30 +0000798 switch (len) {
799 case 0:
800 // Initial dummy fence;
801 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000802 case sizeof(struct RTTInfo):
803 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
804 handleRTTPong(rttInfo);
805 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000806 default:
807 vlog.error("Fence response of unexpected size received");
808 }
809}
810
Pierre Ossman1b478e52011-11-15 12:08:30 +0000811void VNCSConnectionST::enableContinuousUpdates(bool enable,
812 int x, int y, int w, int h)
813{
814 Rect rect;
815
816 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
817 throw Exception("Client tried to enable continuous updates when not allowed");
818
819 continuousUpdates = enable;
820
821 rect.setXYWH(x, y, w, h);
822 cuRegion.reset(rect);
823
824 if (enable) {
825 requested.clear();
826 writeFramebufferUpdate();
827 } else {
828 writer()->writeEndOfContinuousUpdates();
829 }
830}
831
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000832// supportsLocalCursor() is called whenever the status of
833// cp.supportsLocalCursor has changed. If the client does now support local
834// cursor, we make sure that the old server-side rendered cursor is cleaned up
835// and the cursor is sent to the client.
836
837void VNCSConnectionST::supportsLocalCursor()
838{
Pierre Ossman324043e2017-08-16 16:26:11 +0200839 if (cp.supportsLocalCursorWithAlpha ||
840 cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200841 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000842 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000843 setCursor();
844 }
845}
846
Pierre Ossman2c764942011-11-14 15:54:30 +0000847void VNCSConnectionST::supportsFence()
848{
849 writer()->writeFence(fenceFlagRequest, 0, NULL);
850}
851
Pierre Ossman1b478e52011-11-15 12:08:30 +0000852void VNCSConnectionST::supportsContinuousUpdates()
853{
854 // We refuse to use continuous updates if we cannot monitor the buffer
855 // usage using fences.
856 if (!cp.supportsFence)
857 return;
858
859 writer()->writeEndOfContinuousUpdates();
860}
861
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100862void VNCSConnectionST::supportsLEDState()
863{
864 writer()->writeLEDState();
865}
866
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000867
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000868bool VNCSConnectionST::handleTimeout(Timer* t)
869{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000870 try {
Pierre Ossmana40ab202016-04-29 15:35:56 +0200871 if (t == &congestionTimer)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000872 updateCongestion();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000873 } catch (rdr::Exception& e) {
874 close(e.str());
875 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000876
877 return false;
878}
879
Pierre Ossman851e6802017-09-12 16:44:44 +0200880bool VNCSConnectionST::isShiftPressed()
881{
882 std::map<rdr::U32, rdr::U32>::const_iterator iter;
883
884 for (iter = pressedKeys.begin(); iter != pressedKeys.end(); ++iter) {
885 if (iter->second == XK_Shift_L)
886 return true;
887 if (iter->second == XK_Shift_R)
888 return true;
889 }
890
891 return false;
892}
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000893
Pierre Ossman1b478e52011-11-15 12:08:30 +0000894void VNCSConnectionST::writeRTTPing()
895{
896 struct RTTInfo rttInfo;
897
898 if (!cp.supportsFence)
899 return;
900
901 memset(&rttInfo, 0, sizeof(struct RTTInfo));
902
903 gettimeofday(&rttInfo.tv, NULL);
904 rttInfo.offset = sock->outStream().length();
905 rttInfo.inFlight = rttInfo.offset - ackedOffset;
906
907 // We need to make sure any old update are already processed by the
908 // time we get the response back. This allows us to reliably throttle
909 // back on client overload, as well as network overload.
910 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
911 sizeof(struct RTTInfo), (const char*)&rttInfo);
912
913 pingCounter++;
914
915 sentOffset = rttInfo.offset;
916
917 // Let some data flow before we adjust the settings
918 if (!congestionTimer.isStarted())
919 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
920}
921
922void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
923{
924 unsigned rtt, delay;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000925
926 pingCounter--;
927
928 rtt = msSince(&rttInfo.tv);
929 if (rtt < 1)
930 rtt = 1;
931
932 ackedOffset = rttInfo.offset;
933
934 // Try to estimate wire latency by tracking lowest seen latency
935 if (rtt < baseRTT)
936 baseRTT = rtt;
937
938 if (rttInfo.inFlight > congWindow) {
939 seenCongestion = true;
940
941 // Estimate added delay because of overtaxed buffers
942 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
943
944 if (delay < rtt)
945 rtt -= delay;
946 else
947 rtt = 1;
948
949 // If we underestimate the congestion window, then we'll get a latency
950 // that's less than the wire latency, which will confuse other portions
951 // of the code.
952 if (rtt < baseRTT)
953 rtt = baseRTT;
954 }
955
956 // We only keep track of the minimum latency seen (for a given interval)
klemens0536d092017-01-28 20:56:56 +0100957 // on the basis that we want to avoid continuous buffer issue, but don't
Pierre Ossman1b478e52011-11-15 12:08:30 +0000958 // mind (or even approve of) bursts.
959 if (rtt < minRTT)
960 minRTT = rtt;
961}
962
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000963bool VNCSConnectionST::isCongested()
964{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000965 int offset;
966
967 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200968 sock->outStream().flush();
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000969 if (sock->outStream().bufferUsage() > 0)
970 return true;
971
Pierre Ossman1b478e52011-11-15 12:08:30 +0000972 if (!cp.supportsFence)
973 return false;
974
975 // Idle for too long? (and no data on the wire)
976 //
977 // FIXME: This should really just be one baseRTT, but we're getting
978 // problems with triggering the idle timeout on each update.
979 // Maybe we need to use a moving average for the wire latency
980 // instead of baseRTT.
981 if ((sentOffset == ackedOffset) &&
982 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
983
984#ifdef CONGESTION_DEBUG
985 if (congWindow > INITIAL_WINDOW)
986 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
987 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
988#endif
989
990 // Close congestion window and allow a transfer
991 // FIXME: Reset baseRTT like Linux Vegas?
992 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
993
994 return false;
995 }
996
997 offset = sock->outStream().length();
998
999 // FIXME: Should we compensate for non-update data?
1000 // (i.e. use sentOffset instead of offset)
1001 if ((offset - ackedOffset) < congWindow)
1002 return false;
1003
1004 // If we just have one outstanding "ping", that means the client has
1005 // started receiving our update. In order to not regress compared to
1006 // before we had congestion avoidance, we allow another update here.
1007 // This could further clog up the tubes, but congestion control isn't
1008 // really working properly right now anyway as the wire would otherwise
1009 // be idle for at least RTT/2.
1010 if (pingCounter == 1)
1011 return false;
1012
1013 return true;
1014}
1015
1016
1017void VNCSConnectionST::updateCongestion()
1018{
1019 unsigned diff;
1020
1021 if (!seenCongestion)
1022 return;
1023
1024 diff = minRTT - baseRTT;
1025
1026 if (diff > __rfbmin(100, baseRTT)) {
1027 // Way too fast
1028 congWindow = congWindow * baseRTT / minRTT;
1029 } else if (diff > __rfbmin(50, baseRTT/2)) {
1030 // Slightly too fast
1031 congWindow -= 4096;
1032 } else if (diff < 5) {
1033 // Way too slow
1034 congWindow += 8192;
1035 } else if (diff < 25) {
1036 // Too slow
1037 congWindow += 4096;
1038 }
1039
1040 if (congWindow < MINIMUM_WINDOW)
1041 congWindow = MINIMUM_WINDOW;
1042 if (congWindow > MAXIMUM_WINDOW)
1043 congWindow = MAXIMUM_WINDOW;
1044
1045#ifdef CONGESTION_DEBUG
1046 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
1047 minRTT, baseRTT, congWindow / 1024,
1048 congWindow * 8.0 / baseRTT / 1000.0);
1049
1050#ifdef TCP_INFO
1051 struct tcp_info tcp_info;
1052 socklen_t tcp_info_length;
1053
1054 tcp_info_length = sizeof(tcp_info);
1055 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
1056 (void *)&tcp_info, &tcp_info_length) == 0) {
1057 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
1058 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
1059 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
1060 }
1061#endif
1062
1063#endif
1064
1065 minRTT = -1;
1066 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001067}
1068
1069
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001070void VNCSConnectionST::writeFramebufferUpdate()
1071{
Pierre Ossman2c764942011-11-14 15:54:30 +00001072 // We're in the middle of processing a command that's supposed to be
1073 // synchronised. Allowing an update to slip out right now might violate
1074 // that synchronisation.
1075 if (syncFence)
1076 return;
1077
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001078 // We try to aggregate responses, so don't send out anything whilst we
1079 // still have incoming messages. processMessages() will give us another
1080 // chance to run once things are idle.
1081 if (inProcessMessages)
1082 return;
1083
Pierre Ossman1b478e52011-11-15 12:08:30 +00001084 if (state() != RFBSTATE_NORMAL)
1085 return;
1086 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +00001087 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +00001088
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001089 // Check that we actually have some space on the link and retry in a
1090 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +02001091 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001092 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001093
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001094 // Updates often consists of many small writes, and in continuous
1095 // mode, we will also have small fence messages around the update. We
1096 // need to aggregate these in order to not clog up TCP's congestion
1097 // window.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +02001098 sock->cork(true);
Pierre Ossman36dadf82011-11-15 12:11:32 +00001099
Pierre Ossmane9962f72009-04-23 12:31:42 +00001100 // First take care of any updates that cannot contain framebuffer data
1101 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001102 writeNoDataUpdate();
1103
1104 // Then real data (if possible)
1105 writeDataUpdate();
1106
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +02001107 sock->cork(false);
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001108}
1109
1110void VNCSConnectionST::writeNoDataUpdate()
1111{
1112 if (!writer()->needNoDataUpdate())
1113 return;
1114
1115 writer()->writeNoDataUpdate();
1116
1117 // Make sure no data update is sent until next request
1118 requested.clear();
1119}
1120
1121void VNCSConnectionST::writeDataUpdate()
1122{
1123 Region req;
1124 UpdateInfo ui;
1125 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +01001126 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001127
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001128 updates.enable_copyrect(cp.useCopyRect);
1129
Pierre Ossman6e49e952016-10-07 15:59:38 +02001130 // See if we are allowed to send anything right now (the framebuffer
1131 // might have changed in ways we haven't yet been informed of).
Pierre Ossmanbbf955e2011-11-08 12:44:10 +00001132 if (!server->checkUpdate())
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001133 return;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +00001134
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001135 // See what the client has requested (if anything)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001136 if (continuousUpdates)
1137 req = cuRegion.union_(requested);
1138 else
1139 req = requested;
1140
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001141 if (req.is_empty())
1142 return;
1143
1144 // Get the lists of updates. Prior to exporting the data to the `ui' object,
1145 // getUpdateInfo() will normalize the `updates' object such way that its
1146 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +00001147 updates.getUpdateInfo(&ui, req);
1148 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001149
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001150 // If the previous position of the rendered cursor overlaps the source of the
1151 // copy, then when the copy happens the corresponding rectangle in the
1152 // destination will be wrong, so add it to the changed region.
1153
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001154 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
1155 Region bogusCopiedCursor;
1156
1157 bogusCopiedCursor.copyFrom(damagedCursorRegion);
1158 bogusCopiedCursor.translate(ui.copy_delta);
1159 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001160 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001161 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001162 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001163 }
1164 }
1165
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001166 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001167 // the changed region.
1168
1169 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001170 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001171 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001172 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001173 removeRenderedCursor = false;
1174 }
1175
1176 // Return if there is nothing to send the client.
1177
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001178 if (updates.is_empty() && !writer()->needFakeUpdate() && !updateRenderedCursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001179 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001180
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001181 // The `updates' object could change, make sure we have valid update info.
1182
1183 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001184 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001185
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001186 // If the client needs a server-side rendered cursor, work out the cursor
1187 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1188 // with the update region, we need to draw the rendered cursor regardless of
1189 // whether it has changed.
1190
Pierre Ossman24684e52016-12-05 16:58:19 +01001191 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001192 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001193 Rect renderedCursorRect;
1194
Pierre Ossman24684e52016-12-05 16:58:19 +01001195 cursor = server->getRenderedCursor();
1196
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001197 renderedCursorRect
Pierre Ossman24684e52016-12-05 16:58:19 +01001198 = cursor->getEffectiveRect().intersect(req.get_bounding_rect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001199
1200 if (renderedCursorRect.is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001201 cursor = NULL;
1202 } else if (!updateRenderedCursor &&
1203 ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001204 .intersect(renderedCursorRect).is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001205 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001206 }
1207
Pierre Ossman5c037202016-12-05 17:00:35 +01001208 if (cursor) {
1209 updates.subtract(renderedCursorRect);
1210 updates.getUpdateInfo(&ui, req);
1211 }
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001212
1213 damagedCursorRegion.assign_union(renderedCursorRect);
1214 updateRenderedCursor = false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001215 }
1216
Pierre Ossman24684e52016-12-05 16:58:19 +01001217 if (ui.is_empty() && !writer()->needFakeUpdate() && !cursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001218 return;
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001219
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001220 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001221
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001222 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001223
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001224 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001225
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001226 // The request might be for just part of the screen, so we cannot
1227 // just clear the entire update tracker.
1228 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001229
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001230 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001231}
1232
1233
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001234void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1235{
1236 if (!authenticated())
1237 return;
1238
1239 cp.screenLayout = server->screenLayout;
1240
1241 if (state() != RFBSTATE_NORMAL)
1242 return;
1243
1244 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1245 cp.screenLayout);
1246 writeFramebufferUpdate();
1247}
1248
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001249
1250// setCursor() is called whenever the cursor has changed shape or pixel format.
1251// If the client supports local cursor then it will arrange for the cursor to
1252// be sent to the client.
1253
1254void VNCSConnectionST::setCursor()
1255{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001256 if (state() != RFBSTATE_NORMAL)
1257 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001258
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001259 // We need to blank out the client's cursor or there will be two
Pierre Ossman25db44a2017-11-16 16:40:44 +01001260 if (needRenderedCursor()) {
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001261 cp.setCursor(emptyCursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001262 clientHasCursor = false;
1263 } else {
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001264 cp.setCursor(*server->cursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001265 clientHasCursor = true;
1266 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001267
Pierre Ossman8053c8e2017-02-21 12:59:04 +01001268 if (!writer()->writeSetCursorWithAlpha()) {
1269 if (!writer()->writeSetCursor()) {
1270 if (!writer()->writeSetXCursor()) {
1271 // No client support
1272 return;
1273 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001274 }
1275 }
1276
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001277 writeFramebufferUpdate();
1278}
1279
1280void VNCSConnectionST::setDesktopName(const char *name)
1281{
1282 cp.setName(name);
1283
1284 if (state() != RFBSTATE_NORMAL)
1285 return;
1286
1287 if (!writer()->writeSetDesktopName()) {
1288 fprintf(stderr, "Client does not support desktop rename\n");
1289 return;
1290 }
1291
1292 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001293}
1294
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001295void VNCSConnectionST::setLEDState(unsigned int ledstate)
1296{
1297 if (state() != RFBSTATE_NORMAL)
1298 return;
1299
1300 cp.setLEDState(ledstate);
1301
1302 if (!writer()->writeLEDState()) {
1303 // No client support
1304 return;
1305 }
1306
1307 writeFramebufferUpdate();
1308}
1309
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001310void VNCSConnectionST::setSocketTimeouts()
1311{
1312 int timeoutms = rfb::Server::clientWaitTimeMillis;
1313 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1314 if (timeoutms == 0)
1315 timeoutms = -1;
1316 sock->inStream().setTimeout(timeoutms);
1317 sock->outStream().setTimeout(timeoutms);
1318}
1319
1320char* VNCSConnectionST::getStartTime()
1321{
1322 char* result = ctime(&startTime);
1323 result[24] = '\0';
1324 return result;
1325}
1326
1327void VNCSConnectionST::setStatus(int status)
1328{
1329 switch (status) {
1330 case 0:
1331 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1332 break;
1333 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001334 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001335 break;
1336 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001337 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001338 break;
1339 }
1340 framebufferUpdateRequest(server->pb->getRect(), false);
1341}
1342int VNCSConnectionST::getStatus()
1343{
1344 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1345 return 0;
1346 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1347 return 1;
1348 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1349 return 2;
1350 return 4;
1351}
1352