blob: 7b7913913f27c50415d4c9bba5e62c458122877d [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossman8c3bd692018-03-22 15:58:54 +01002 * Copyright 2009-2018 Pierre Ossman for Cendio AB
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +02003 * Copyright 2018 Peter Astrand for Cendio AB
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00004 *
5 * This is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This software is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this software; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
18 * USA.
19 */
20
Pierre Ossmana830bec2011-11-08 12:12:02 +000021#include <network/TcpSocket.h>
Pierre Ossman707fa122015-12-11 20:21:20 +010022
23#include <rfb/ComparingUpdateTracker.h>
24#include <rfb/Encoder.h>
25#include <rfb/KeyRemapper.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000026#include <rfb/LogWriter.h>
Adam Tkac5a0caed2010-04-23 13:58:10 +000027#include <rfb/Security.h>
Pierre Ossman707fa122015-12-11 20:21:20 +010028#include <rfb/ServerCore.h>
29#include <rfb/SMsgWriter.h>
30#include <rfb/VNCServerST.h>
31#include <rfb/VNCSConnectionST.h>
Pierre Ossmanc5e25602009-03-20 12:59:05 +000032#include <rfb/screenTypes.h>
Pierre Ossman2c764942011-11-14 15:54:30 +000033#include <rfb/fenceTypes.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010034#include <rfb/ledStates.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010035#define XK_LATIN1
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000036#define XK_MISCELLANY
37#define XK_XKB_KEYS
38#include <rfb/keysymdef.h>
39
40using namespace rfb;
41
42static LogWriter vlog("VNCSConnST");
43
Pierre Ossman71ca8d52017-09-15 11:03:12 +020044static Cursor emptyCursor(0, 0, Point(0, 0), NULL);
45
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000046VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
47 bool reverse)
Pierre Ossman7069bdd2015-02-06 14:41:58 +010048 : sock(s), reverseConnection(reverse),
Pierre Ossman36304752017-10-04 16:21:57 +020049 inProcessMessages(false),
Pierre Ossmanb8b1e962012-07-20 10:47:00 +000050 pendingSyncFence(false), syncFence(false), fenceFlags(0),
Pierre Ossmana99d14d2015-12-13 15:43:46 +010051 fenceDataLen(0), fenceData(NULL), congestionTimer(this),
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +020052 losslessTimer(this), server(server_), updates(false),
Pierre Ossman671d2ef2015-06-09 16:09:06 +020053 updateRenderedCursor(false), removeRenderedCursor(false),
Pierre Ossmana40ab202016-04-29 15:35:56 +020054 continuousUpdates(false), encodeManager(this), pointerEventTime(0),
Pierre Ossman25db44a2017-11-16 16:40:44 +010055 clientHasCursor(false),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000056 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000057{
58 setStreams(&sock->inStream(), &sock->outStream());
59 peerEndpoint.buf = sock->getPeerEndpoint();
60 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
61
62 // Configure the socket
63 setSocketTimeouts();
64 lastEventTime = time(0);
65
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000066 server->clients.push_front(this);
67}
68
69
70VNCSConnectionST::~VNCSConnectionST()
71{
72 // If we reach here then VNCServerST is deleting us!
73 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
74 peerEndpoint.buf,
75 (closeReason.buf) ? closeReason.buf : "");
76
77 // Release any keys the client still had pressed
Pierre Ossman16e1dcb2017-05-16 14:33:43 +020078 while (!pressedKeys.empty()) {
79 rdr::U32 keysym, keycode;
80
81 keysym = pressedKeys.begin()->second;
82 keycode = pressedKeys.begin()->first;
83 pressedKeys.erase(pressedKeys.begin());
84
85 vlog.debug("Releasing key 0x%x / 0x%x on client disconnect",
86 keysym, keycode);
87 server->desktop->keyEvent(keysym, keycode, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +020088 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +020089
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000090 if (server->pointerClient == this)
91 server->pointerClient = 0;
92
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000093 // Remove this client from the server
94 server->clients.remove(this);
95
Pierre Ossman2c764942011-11-14 15:54:30 +000096 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000097}
98
99
100// Methods called from VNCServerST
101
102bool VNCSConnectionST::init()
103{
104 try {
105 initialiseProtocol();
106 } catch (rdr::Exception& e) {
107 close(e.str());
108 return false;
109 }
110 return true;
111}
112
113void VNCSConnectionST::close(const char* reason)
114{
115 // Log the reason for the close
116 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000117 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000118 else
119 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
120
121 if (authenticated()) {
122 server->lastDisconnectTime = time(0);
123 }
124
125 // Just shutdown the socket and mark our state as closing. Eventually the
126 // calling code will call VNCServerST's removeSocket() method causing us to
127 // be deleted.
128 sock->shutdown();
129 setState(RFBSTATE_CLOSING);
130}
131
132
133void VNCSConnectionST::processMessages()
134{
135 if (state() == RFBSTATE_CLOSING) return;
136 try {
137 // - Now set appropriate socket timeouts and process data
138 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000139
140 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000141
Pierre Ossmana830bec2011-11-08 12:12:02 +0000142 // Get the underlying TCP layer to build large packets if we send
143 // multiple small responses.
Peter Åstrand (astrand)01dc1a62017-10-10 12:56:04 +0200144 sock->cork(true);
Pierre Ossmana830bec2011-11-08 12:12:02 +0000145
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000146 while (getInStream()->checkNoWait(1)) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000147 if (pendingSyncFence) {
148 syncFence = true;
149 pendingSyncFence = false;
150 }
151
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000152 processMsg();
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000153
Pierre Ossman2c764942011-11-14 15:54:30 +0000154 if (syncFence) {
155 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
156 syncFence = false;
157 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000158 }
159
Pierre Ossmana830bec2011-11-08 12:12:02 +0000160 // Flush out everything in case we go idle after this.
Peter Åstrand (astrand)01dc1a62017-10-10 12:56:04 +0200161 sock->cork(false);
Pierre Ossmana830bec2011-11-08 12:12:02 +0000162
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000163 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000164
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000165 // If there were anything requiring an update, try to send it here.
166 // We wait until now with this to aggregate responses and to give
167 // higher priority to user actions such as keyboard and pointer events.
168 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000169 } catch (rdr::EndOfStream&) {
170 close("Clean disconnection");
171 } catch (rdr::Exception &e) {
172 close(e.str());
173 }
174}
175
Pierre Ossmand408ca52016-04-29 14:26:05 +0200176void VNCSConnectionST::flushSocket()
177{
178 if (state() == RFBSTATE_CLOSING) return;
179 try {
180 setSocketTimeouts();
181 sock->outStream().flush();
Pierre Ossmana40ab202016-04-29 15:35:56 +0200182 // Flushing the socket might release an update that was previously
183 // delayed because of congestion.
184 if (sock->outStream().bufferUsage() == 0)
185 writeFramebufferUpdate();
Pierre Ossmand408ca52016-04-29 14:26:05 +0200186 } catch (rdr::Exception &e) {
187 close(e.str());
188 }
189}
190
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000191void VNCSConnectionST::pixelBufferChange()
192{
193 try {
194 if (!authenticated()) return;
Pierre Ossman6094ced2018-10-05 17:24:51 +0200195 if (cp.width && cp.height &&
196 (server->getPixelBuffer()->width() != cp.width ||
197 server->getPixelBuffer()->height() != cp.height))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000198 {
199 // We need to clip the next update to the new size, but also add any
200 // extra bits if it's bigger. If we wanted to do this exactly, something
201 // like the code below would do it, but at the moment we just update the
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200202 // entire new size. However, we do need to clip the damagedCursorRegion
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000203 // because that might be added to updates in writeFramebufferUpdate().
204
205 //updates.intersect(server->pb->getRect());
206 //
207 //if (server->pb->width() > cp.width)
208 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
209 // server->pb->height()));
210 //if (server->pb->height() > cp.height)
211 // updates.add_changed(Rect(0, cp.height, cp.width,
212 // server->pb->height()));
213
Pierre Ossman6094ced2018-10-05 17:24:51 +0200214 damagedCursorRegion.assign_intersect(server->getPixelBuffer()->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000215
Pierre Ossman6094ced2018-10-05 17:24:51 +0200216 cp.width = server->getPixelBuffer()->width();
217 cp.height = server->getPixelBuffer()->height();
218 cp.screenLayout = server->getScreenLayout();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000219 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000220 // We should only send EDS to client asking for both
221 if (!writer()->writeExtendedDesktopSize()) {
222 if (!writer()->writeSetDesktopSize()) {
223 close("Client does not support desktop resize");
224 return;
225 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000226 }
227 }
Pierre Ossman6b2f1132016-11-30 08:03:35 +0100228
229 // Drop any lossy tracking that is now outside the framebuffer
Pierre Ossman6094ced2018-10-05 17:24:51 +0200230 encodeManager.pruneLosslessRefresh(Region(server->getPixelBuffer()->getRect()));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000231 }
232 // Just update the whole screen at the moment because we're too lazy to
233 // work out what's actually changed.
234 updates.clear();
Pierre Ossman6094ced2018-10-05 17:24:51 +0200235 updates.add_changed(server->getPixelBuffer()->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000236 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000237 } catch(rdr::Exception &e) {
238 close(e.str());
239 }
240}
241
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000242void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000243{
244 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000245 writeFramebufferUpdate();
246 } catch(rdr::Exception &e) {
247 close(e.str());
248 }
249}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000250
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000251void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
252{
253 try {
254 screenLayoutChange(reason);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100255 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000256 } catch(rdr::Exception &e) {
257 close(e.str());
258 }
259}
260
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000261void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000262{
263 try {
264 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
265 } catch(rdr::Exception& e) {
266 close(e.str());
267 }
268}
269
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000270void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000271{
272 try {
273 if (!(accessRights & AccessCutText)) return;
274 if (!rfb::Server::sendCutText) return;
275 if (state() == RFBSTATE_NORMAL)
276 writer()->writeServerCutText(str, len);
277 } catch(rdr::Exception& e) {
278 close(e.str());
279 }
280}
281
Peter Åstrandc39e0782009-01-15 12:21:42 +0000282
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000283void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Åstrandc39e0782009-01-15 12:21:42 +0000284{
Peter Åstrandc39e0782009-01-15 12:21:42 +0000285 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000286 setDesktopName(name);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100287 writeFramebufferUpdate();
Peter Åstrandc39e0782009-01-15 12:21:42 +0000288 } catch(rdr::Exception& e) {
289 close(e.str());
290 }
291}
292
293
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000294void VNCSConnectionST::setCursorOrClose()
295{
296 try {
297 setCursor();
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100298 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000299 } catch(rdr::Exception& e) {
300 close(e.str());
301 }
302}
303
304
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100305void VNCSConnectionST::setLEDStateOrClose(unsigned int state)
306{
307 try {
308 setLEDState(state);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100309 writeFramebufferUpdate();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100310 } catch(rdr::Exception& e) {
311 close(e.str());
312 }
313}
314
315
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000316int VNCSConnectionST::checkIdleTimeout()
317{
318 int idleTimeout = rfb::Server::idleTimeout;
319 if (idleTimeout == 0) return 0;
320 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
321 idleTimeout = 15; // minimum of 15 seconds while authenticating
322 time_t now = time(0);
323 if (now < lastEventTime) {
324 // Someone must have set the time backwards. Set lastEventTime so that the
325 // idleTimeout will count from now.
326 vlog.info("Time has gone backwards - resetting idle timeout");
327 lastEventTime = now;
328 }
329 int timeLeft = lastEventTime + idleTimeout - now;
330 if (timeLeft < -60) {
331 // Our callback is over a minute late - someone must have set the time
332 // forwards. Set lastEventTime so that the idleTimeout will count from
333 // now.
334 vlog.info("Time has gone forwards - resetting idle timeout");
335 lastEventTime = now;
336 return secsToMillis(idleTimeout);
337 }
338 if (timeLeft <= 0) {
339 close("Idle timeout");
340 return 0;
341 }
342 return secsToMillis(timeLeft);
343}
344
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000345
346bool VNCSConnectionST::getComparerState()
347{
348 // We interpret a low compression level as an indication that the client
349 // wants to prioritise CPU usage over bandwidth, and hence disable the
350 // comparing update tracker.
351 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
352}
353
354
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000355// renderedCursorChange() is called whenever the server-side rendered cursor
356// changes shape or position. It ensures that the next update will clean up
357// the old rendered cursor and if necessary draw the new rendered cursor.
358
359void VNCSConnectionST::renderedCursorChange()
360{
361 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200362 // Are we switching between client-side and server-side cursor?
Pierre Ossman25db44a2017-11-16 16:40:44 +0100363 if (clientHasCursor == needRenderedCursor())
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200364 setCursorOrClose();
Pierre Ossman25db44a2017-11-16 16:40:44 +0100365 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
Pierre Ossman330ca422017-11-06 13:15:55 +0100366 if (hasRenderedCursor)
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000367 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000368 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200369 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000370 writeFramebufferUpdateOrClose();
371 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000372}
373
374// needRenderedCursor() returns true if this client needs the server-side
375// rendered cursor. This may be because it does not support local cursor or
376// because the current cursor position has not been set by this client.
377// Unfortunately we can't know for sure when the current cursor position has
378// been set by this client. We guess that this is the case when the current
379// cursor position is the same as the last pointer event from this client, or
380// if it is a very short time since this client's last pointer event (up to a
381// second). [ Ideally we should do finer-grained timing here and make the time
382// configurable, but I don't think it's that important. ]
383
384bool VNCSConnectionST::needRenderedCursor()
385{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100386 if (state() != RFBSTATE_NORMAL)
387 return false;
388
Pierre Ossman324043e2017-08-16 16:26:11 +0200389 if (!cp.supportsLocalCursorWithAlpha &&
390 !cp.supportsLocalCursor && !cp.supportsLocalXCursor)
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100391 return true;
Pierre Ossman6094ced2018-10-05 17:24:51 +0200392 if (!server->getCursorPos().equals(pointerEventPos) &&
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100393 (time(0) - pointerEventTime) > 0)
394 return true;
395
396 return false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000397}
398
399
400void VNCSConnectionST::approveConnectionOrClose(bool accept,
401 const char* reason)
402{
403 try {
404 approveConnection(accept, reason);
405 } catch (rdr::Exception& e) {
406 close(e.str());
407 }
408}
409
410
411
412// -=- Callbacks from SConnection
413
414void VNCSConnectionST::authSuccess()
415{
416 lastEventTime = time(0);
417
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000418 // - Set the connection parameters appropriately
Pierre Ossman6094ced2018-10-05 17:24:51 +0200419 cp.width = server->getPixelBuffer()->width();
420 cp.height = server->getPixelBuffer()->height();
421 cp.screenLayout = server->getScreenLayout();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000422 cp.setName(server->getName());
Pierre Ossman6094ced2018-10-05 17:24:51 +0200423 cp.setLEDState(server->getLEDState());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000424
425 // - Set the default pixel format
Pierre Ossman6094ced2018-10-05 17:24:51 +0200426 cp.setPF(server->getPixelBuffer()->getPF());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000427 char buffer[256];
428 cp.pf().print(buffer, 256);
429 vlog.info("Server default pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000430
431 // - Mark the entire display as "dirty"
Pierre Ossman6094ced2018-10-05 17:24:51 +0200432 updates.add_changed(server->getPixelBuffer()->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000433 startTime = time(0);
434}
435
436void VNCSConnectionST::queryConnection(const char* userName)
437{
438 // - Authentication succeeded - clear from blacklist
439 CharArray name; name.buf = sock->getPeerAddress();
440 server->blHosts->clearBlackmark(name.buf);
441
Pierre Ossmaneef6c9a2018-10-05 17:11:25 +0200442 // - Prepare the desktop that we might be making calls
443 server->startDesktop();
444
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000445 // - Special case to provide a more useful error message
446 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
447 server->authClientCount() > 0) {
448 approveConnection(false, "The server is already in use");
449 return;
450 }
451
452 // - Does the client have the right to bypass the query?
453 if (reverseConnection ||
454 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
455 (accessRights & AccessNoQuery))
456 {
457 approveConnection(true);
458 return;
459 }
460
461 // - Get the server to display an Accept/Reject dialog, if required
Pierre Ossmane6aab242018-10-05 16:59:22 +0200462 server->queryConnection(sock, userName);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000463}
464
465void VNCSConnectionST::clientInit(bool shared)
466{
467 lastEventTime = time(0);
468 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100469 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000470 if (rfb::Server::neverShared) shared = false;
471 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100472 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000473 // - Close all the other connected clients
474 vlog.debug("non-shared connection - closing clients");
475 server->closeClients("Non-shared connection requested", getSock());
476 } else {
477 // - Refuse this connection if there are existing clients, in addition to
478 // this one
479 if (server->authClientCount() > 1) {
480 close("Server is already in use");
481 return;
482 }
483 }
484 }
485 SConnection::clientInit(shared);
486}
487
488void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
489{
490 SConnection::setPixelFormat(pf);
491 char buffer[256];
492 pf.print(buffer, 256);
493 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000494 setCursor();
495}
496
497void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
498{
499 pointerEventTime = lastEventTime = time(0);
500 server->lastUserInputTime = lastEventTime;
501 if (!(accessRights & AccessPtrEvents)) return;
502 if (!rfb::Server::acceptPointerEvents) return;
503 if (!server->pointerClient || server->pointerClient == this) {
504 pointerEventPos = pos;
505 if (buttonMask)
506 server->pointerClient = this;
507 else
508 server->pointerClient = 0;
509 server->desktop->pointerEvent(pointerEventPos, buttonMask);
510 }
511}
512
513
514class VNCSConnectionSTShiftPresser {
515public:
516 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
517 : desktop(desktop_), pressed(false) {}
518 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200519 if (pressed) {
520 vlog.debug("Releasing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200521 desktop->keyEvent(XK_Shift_L, 0, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200522 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000523 }
524 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200525 vlog.debug("Pressing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200526 desktop->keyEvent(XK_Shift_L, 0, true);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000527 pressed = true;
528 }
529 SDesktop* desktop;
530 bool pressed;
531};
532
533// keyEvent() - record in the pressedKeys which keys were pressed. Allow
534// multiple down events (for autorepeat), but only allow a single up event.
Pierre Ossman5ae28212017-05-16 14:30:38 +0200535void VNCSConnectionST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200536 rdr::U32 lookup;
537
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000538 lastEventTime = time(0);
539 server->lastUserInputTime = lastEventTime;
540 if (!(accessRights & AccessKeyEvents)) return;
541 if (!rfb::Server::acceptKeyEvents) return;
542
Pierre Ossman9a153b02015-08-31 10:01:14 +0200543 if (down)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200544 vlog.debug("Key pressed: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200545 else
Pierre Ossman5ae28212017-05-16 14:30:38 +0200546 vlog.debug("Key released: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200547
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000548 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200549 if (server->keyRemapper) {
550 rdr::U32 newkey;
Pierre Ossman5ae28212017-05-16 14:30:38 +0200551 newkey = server->keyRemapper->remapKey(keysym);
552 if (newkey != keysym) {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200553 vlog.debug("Key remapped to 0x%x", newkey);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200554 keysym = newkey;
Pierre Ossman9a153b02015-08-31 10:01:14 +0200555 }
556 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000557
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100558 // Avoid lock keys if we don't know the server state
Pierre Ossman6094ced2018-10-05 17:24:51 +0200559 if ((server->getLEDState() == ledUnknown) &&
Pierre Ossman5ae28212017-05-16 14:30:38 +0200560 ((keysym == XK_Caps_Lock) ||
561 (keysym == XK_Num_Lock) ||
562 (keysym == XK_Scroll_Lock))) {
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100563 vlog.debug("Ignoring lock key (e.g. caps lock)");
564 return;
565 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100566
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100567 // Lock key heuristics
568 // (only for clients that do not support the LED state extension)
569 if (!cp.supportsLEDState) {
570 // Always ignore ScrollLock as we don't have a heuristic
571 // for that
Pierre Ossman5ae28212017-05-16 14:30:38 +0200572 if (keysym == XK_Scroll_Lock) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100573 vlog.debug("Ignoring lock key (e.g. caps lock)");
574 return;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100575 }
576
Pierre Ossman6094ced2018-10-05 17:24:51 +0200577 if (down && (server->getLEDState() != ledUnknown)) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100578 // CapsLock synchronisation heuristic
579 // (this assumes standard interaction between CapsLock the Shift
580 // keys and normal characters)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200581 if (((keysym >= XK_A) && (keysym <= XK_Z)) ||
582 ((keysym >= XK_a) && (keysym <= XK_z))) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100583 bool uppercase, shift, lock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100584
Pierre Ossman5ae28212017-05-16 14:30:38 +0200585 uppercase = (keysym >= XK_A) && (keysym <= XK_Z);
Pierre Ossman851e6802017-09-12 16:44:44 +0200586 shift = isShiftPressed();
Pierre Ossman6094ced2018-10-05 17:24:51 +0200587 lock = server->getLEDState() & ledCapsLock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100588
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100589 if (lock == (uppercase == shift)) {
590 vlog.debug("Inserting fake CapsLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200591 server->desktop->keyEvent(XK_Caps_Lock, 0, true);
592 server->desktop->keyEvent(XK_Caps_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100593 }
594 }
595
596 // NumLock synchronisation heuristic
597 // (this is more cautious because of the differences between Unix,
598 // Windows and macOS)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200599 if (((keysym >= XK_KP_Home) && (keysym <= XK_KP_Delete)) ||
600 ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
601 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal)) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100602 bool number, shift, lock;
603
Pierre Ossman5ae28212017-05-16 14:30:38 +0200604 number = ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
605 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal);
Pierre Ossman851e6802017-09-12 16:44:44 +0200606 shift = isShiftPressed();
Pierre Ossman6094ced2018-10-05 17:24:51 +0200607 lock = server->getLEDState() & ledNumLock;
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100608
609 if (shift) {
610 // We don't know the appropriate NumLock state for when Shift
611 // is pressed as it could be one of:
612 //
613 // a) A Unix client where Shift negates NumLock
614 //
615 // b) A Windows client where Shift only cancels NumLock
616 //
617 // c) A macOS client where Shift doesn't have any effect
618 //
619 } else if (lock == (number == shift)) {
620 vlog.debug("Inserting fake NumLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200621 server->desktop->keyEvent(XK_Num_Lock, 0, true);
622 server->desktop->keyEvent(XK_Num_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100623 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100624 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000625 }
626 }
627
628 // Turn ISO_Left_Tab into shifted Tab.
629 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200630 if (keysym == XK_ISO_Left_Tab) {
Pierre Ossman851e6802017-09-12 16:44:44 +0200631 if (!isShiftPressed())
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000632 shiftPresser.press();
Pierre Ossman5ae28212017-05-16 14:30:38 +0200633 keysym = XK_Tab;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000634 }
635
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200636 // We need to be able to track keys, so generate a fake index when we
637 // aren't given a keycode
638 if (keycode == 0)
639 lookup = 0x80000000 | keysym;
640 else
641 lookup = keycode;
642
643 // We force the same keysym for an already down key for the
644 // sake of sanity
645 if (pressedKeys.find(lookup) != pressedKeys.end())
646 keysym = pressedKeys[lookup];
647
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000648 if (down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200649 pressedKeys[lookup] = keysym;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000650 } else {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200651 if (!pressedKeys.erase(lookup))
Pierre Ossman5ae28212017-05-16 14:30:38 +0200652 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000653 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200654
Pierre Ossman5ae28212017-05-16 14:30:38 +0200655 server->desktop->keyEvent(keysym, keycode, down);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000656}
657
658void VNCSConnectionST::clientCutText(const char* str, int len)
659{
660 if (!(accessRights & AccessCutText)) return;
661 if (!rfb::Server::acceptCutText) return;
662 server->desktop->clientCutText(str, len);
663}
664
665void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
666{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000667 Rect safeRect;
668
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000669 if (!(accessRights & AccessView)) return;
670
671 SConnection::framebufferUpdateRequest(r, incremental);
672
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000673 // Check that the client isn't sending crappy requests
674 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
675 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
676 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000677 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
678 } else {
679 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000680 }
681
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000682 // Just update the requested region.
683 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000684 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000685 if (!incremental || !continuousUpdates)
686 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000687
688 if (!incremental) {
689 // Non-incremental update - treat as if area requested has changed
690 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000691
692 // And send the screen layout to the client (which, unlike the
693 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000694 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000695
696 // We do not send a DesktopSize since it only contains the
697 // framebuffer size (which the client already should know) and
698 // because some clients don't handle extra DesktopSize events
699 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000700 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000701}
702
Pierre Ossman34bb0612009-03-21 21:16:14 +0000703void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
704 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000705{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000706 unsigned int result;
707
Michal Srbb318b8f2014-11-24 13:18:28 +0200708 if (!(accessRights & AccessSetDesktopSize)) return;
709 if (!rfb::Server::acceptSetDesktopSize) return;
710
Pierre Ossman04e62db2009-03-23 16:57:07 +0000711 // Don't bother the desktop with an invalid configuration
712 if (!layout.validate(fb_width, fb_height)) {
713 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
714 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000715 return;
716 }
717
718 // FIXME: the desktop will call back to VNCServerST and an extra set
719 // of ExtendedDesktopSize messages will be sent. This is okay
720 // protocol-wise, but unnecessary.
721 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
722
Pierre Ossman04e62db2009-03-23 16:57:07 +0000723 writer()->writeExtendedDesktopSize(reasonClient, result,
724 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000725
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000726 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000727 if (result == resultSuccess) {
728 if (server->screenLayout != layout)
729 throw Exception("Desktop configured a different screen layout than requested");
730 server->notifyScreenLayoutChange(this);
731 }
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000732}
733
Pierre Ossman2c764942011-11-14 15:54:30 +0000734void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
735{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100736 rdr::U8 type;
737
Pierre Ossman2c764942011-11-14 15:54:30 +0000738 if (flags & fenceFlagRequest) {
739 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000740 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000741
742 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
743 fenceDataLen = len;
744 delete [] fenceData;
Michal Srbf3afa242017-03-27 19:02:15 +0300745 fenceData = NULL;
Pierre Ossman2c764942011-11-14 15:54:30 +0000746 if (len > 0) {
747 fenceData = new char[len];
748 memcpy(fenceData, data, len);
749 }
750
751 return;
752 }
753
754 // We handle everything synchronously so we trivially honor these modes
755 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
756
757 writer()->writeFence(flags, len, data);
758 return;
759 }
760
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100761 if (len < 1)
762 vlog.error("Fence response of unexpected size received");
Pierre Ossman1b478e52011-11-15 12:08:30 +0000763
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100764 type = data[0];
765
766 switch (type) {
Pierre Ossman2c764942011-11-14 15:54:30 +0000767 case 0:
768 // Initial dummy fence;
769 break;
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100770 case 1:
Pierre Ossmanc09e5582015-12-11 20:23:17 +0100771 congestion.gotPong();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000772 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000773 default:
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100774 vlog.error("Fence response of unexpected type received");
Pierre Ossman2c764942011-11-14 15:54:30 +0000775 }
776}
777
Pierre Ossman1b478e52011-11-15 12:08:30 +0000778void VNCSConnectionST::enableContinuousUpdates(bool enable,
779 int x, int y, int w, int h)
780{
781 Rect rect;
782
783 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
784 throw Exception("Client tried to enable continuous updates when not allowed");
785
786 continuousUpdates = enable;
787
788 rect.setXYWH(x, y, w, h);
789 cuRegion.reset(rect);
790
791 if (enable) {
792 requested.clear();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000793 } else {
794 writer()->writeEndOfContinuousUpdates();
795 }
796}
797
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000798// supportsLocalCursor() is called whenever the status of
799// cp.supportsLocalCursor has changed. If the client does now support local
800// cursor, we make sure that the old server-side rendered cursor is cleaned up
801// and the cursor is sent to the client.
802
803void VNCSConnectionST::supportsLocalCursor()
804{
Pierre Ossman387a4172017-11-16 16:44:36 +0100805 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
806 if (hasRenderedCursor && !needRenderedCursor())
807 removeRenderedCursor = true;
808 setCursor();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000809}
810
Pierre Ossman2c764942011-11-14 15:54:30 +0000811void VNCSConnectionST::supportsFence()
812{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100813 char type = 0;
814 writer()->writeFence(fenceFlagRequest, sizeof(type), &type);
Pierre Ossman2c764942011-11-14 15:54:30 +0000815}
816
Pierre Ossman1b478e52011-11-15 12:08:30 +0000817void VNCSConnectionST::supportsContinuousUpdates()
818{
819 // We refuse to use continuous updates if we cannot monitor the buffer
820 // usage using fences.
821 if (!cp.supportsFence)
822 return;
823
824 writer()->writeEndOfContinuousUpdates();
825}
826
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100827void VNCSConnectionST::supportsLEDState()
828{
829 writer()->writeLEDState();
830}
831
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000832
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000833bool VNCSConnectionST::handleTimeout(Timer* t)
834{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000835 try {
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +0200836 if ((t == &congestionTimer) ||
837 (t == &losslessTimer))
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100838 writeFramebufferUpdate();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000839 } catch (rdr::Exception& e) {
840 close(e.str());
841 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000842
843 return false;
844}
845
Pierre Ossman851e6802017-09-12 16:44:44 +0200846bool VNCSConnectionST::isShiftPressed()
847{
848 std::map<rdr::U32, rdr::U32>::const_iterator iter;
849
850 for (iter = pressedKeys.begin(); iter != pressedKeys.end(); ++iter) {
851 if (iter->second == XK_Shift_L)
852 return true;
853 if (iter->second == XK_Shift_R)
854 return true;
855 }
856
857 return false;
858}
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000859
Pierre Ossman1b478e52011-11-15 12:08:30 +0000860void VNCSConnectionST::writeRTTPing()
861{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100862 char type;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000863
864 if (!cp.supportsFence)
865 return;
866
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100867 congestion.updatePosition(sock->outStream().length());
Pierre Ossman1b478e52011-11-15 12:08:30 +0000868
869 // We need to make sure any old update are already processed by the
870 // time we get the response back. This allows us to reliably throttle
871 // back on client overload, as well as network overload.
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100872 type = 1;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000873 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100874 sizeof(type), &type);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000875
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100876 congestion.sentPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000877}
878
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000879bool VNCSConnectionST::isCongested()
880{
Pierre Ossmance261812018-07-17 15:01:53 +0200881 int eta;
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100882
883 congestionTimer.stop();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000884
885 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200886 sock->outStream().flush();
Pierre Ossman8cf71632016-03-11 09:38:08 +0100887 congestion.debugTrace("congestion-trace.csv", sock->getFd());
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000888 if (sock->outStream().bufferUsage() > 0)
889 return true;
890
Pierre Ossman1b478e52011-11-15 12:08:30 +0000891 if (!cp.supportsFence)
892 return false;
893
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100894 congestion.updatePosition(sock->outStream().length());
895 if (!congestion.isCongested())
Pierre Ossman1b478e52011-11-15 12:08:30 +0000896 return false;
897
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100898 eta = congestion.getUncongestedETA();
899 if (eta >= 0)
900 congestionTimer.start(eta);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000901
902 return true;
903}
904
905
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000906void VNCSConnectionST::writeFramebufferUpdate()
907{
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100908 congestion.updatePosition(sock->outStream().length());
909
Pierre Ossman2c764942011-11-14 15:54:30 +0000910 // We're in the middle of processing a command that's supposed to be
911 // synchronised. Allowing an update to slip out right now might violate
912 // that synchronisation.
913 if (syncFence)
914 return;
915
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000916 // We try to aggregate responses, so don't send out anything whilst we
917 // still have incoming messages. processMessages() will give us another
918 // chance to run once things are idle.
919 if (inProcessMessages)
920 return;
921
Pierre Ossman1b478e52011-11-15 12:08:30 +0000922 if (state() != RFBSTATE_NORMAL)
923 return;
924 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000925 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000926
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000927 // Check that we actually have some space on the link and retry in a
928 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +0200929 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000930 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000931
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100932 // Updates often consists of many small writes, and in continuous
933 // mode, we will also have small fence messages around the update. We
934 // need to aggregate these in order to not clog up TCP's congestion
935 // window.
Peter Åstrand (astrand)01dc1a62017-10-10 12:56:04 +0200936 sock->cork(true);
Pierre Ossman36dadf82011-11-15 12:11:32 +0000937
Pierre Ossmane9962f72009-04-23 12:31:42 +0000938 // First take care of any updates that cannot contain framebuffer data
939 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100940 writeNoDataUpdate();
941
942 // Then real data (if possible)
943 writeDataUpdate();
944
Peter Åstrand (astrand)01dc1a62017-10-10 12:56:04 +0200945 sock->cork(false);
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100946
947 congestion.updatePosition(sock->outStream().length());
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100948}
949
950void VNCSConnectionST::writeNoDataUpdate()
951{
952 if (!writer()->needNoDataUpdate())
953 return;
954
955 writer()->writeNoDataUpdate();
956
957 // Make sure no data update is sent until next request
958 requested.clear();
959}
960
961void VNCSConnectionST::writeDataUpdate()
962{
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100963 Region req, pending;
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100964 UpdateInfo ui;
965 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +0100966 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000967
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000968 updates.enable_copyrect(cp.useCopyRect);
969
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100970 // See what the client has requested (if anything)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000971 if (continuousUpdates)
972 req = cuRegion.union_(requested);
973 else
974 req = requested;
975
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100976 if (req.is_empty())
977 return;
978
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100979 // Get any framebuffer changes we haven't yet been informed of
980 pending = server->getPendingRegion();
981
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100982 // Get the lists of updates. Prior to exporting the data to the `ui' object,
983 // getUpdateInfo() will normalize the `updates' object such way that its
984 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +0000985 updates.getUpdateInfo(&ui, req);
986 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000987
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000988 // If the previous position of the rendered cursor overlaps the source of the
989 // copy, then when the copy happens the corresponding rectangle in the
990 // destination will be wrong, so add it to the changed region.
991
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200992 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
993 Region bogusCopiedCursor;
994
Pierre Ossman74385d32018-03-22 16:00:18 +0100995 bogusCopiedCursor = damagedCursorRegion;
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200996 bogusCopiedCursor.translate(ui.copy_delta);
Pierre Ossman6094ced2018-10-05 17:24:51 +0200997 bogusCopiedCursor.assign_intersect(server->getPixelBuffer()->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000998 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000999 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001000 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001001 }
1002 }
1003
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001004 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001005 // the changed region.
1006
1007 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001008 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001009 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001010 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001011 removeRenderedCursor = false;
1012 }
1013
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001014 // If we need a full cursor update then make sure its entire region
1015 // is marked as changed.
1016
1017 if (updateRenderedCursor) {
1018 updates.add_changed(server->getRenderedCursor()->getEffectiveRect());
1019 needNewUpdateInfo = true;
1020 updateRenderedCursor = false;
1021 }
1022
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001023 // The `updates' object could change, make sure we have valid update info.
1024
1025 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001026 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001027
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001028 // If there are queued updates then we cannot safely send an update
1029 // without risking a partially updated screen
1030
1031 if (!pending.is_empty()) {
1032 // However we might still be able to send a lossless refresh
1033 req.assign_subtract(pending);
1034 req.assign_subtract(ui.changed);
1035 req.assign_subtract(ui.copied);
1036
1037 ui.changed.clear();
1038 ui.copied.clear();
1039 }
1040
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001041 // Does the client need a server-side rendered cursor?
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001042
Pierre Ossman24684e52016-12-05 16:58:19 +01001043 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001044 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001045 Rect renderedCursorRect;
1046
Pierre Ossman24684e52016-12-05 16:58:19 +01001047 cursor = server->getRenderedCursor();
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001048 renderedCursorRect = cursor->getEffectiveRect();
Pierre Ossman24684e52016-12-05 16:58:19 +01001049
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001050 // Check that we don't try to copy over the cursor area, and
1051 // if that happens we need to treat it as changed so that we can
1052 // re-render it
1053 if (!ui.copied.intersect(renderedCursorRect).is_empty()) {
1054 ui.changed.assign_union(ui.copied.intersect(renderedCursorRect));
1055 ui.copied.assign_subtract(renderedCursorRect);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001056 }
1057
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001058 // Track where we've rendered the cursor
1059 damagedCursorRegion.assign_union(ui.changed.intersect(renderedCursorRect));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001060 }
1061
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001062 // Return if there is nothing to send the client.
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +02001063 if (ui.is_empty() && !writer()->needFakeUpdate()) {
1064 int eta;
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001065
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +02001066 // Any lossless refresh that needs handling?
1067 if (!encodeManager.needsLosslessRefresh(req))
1068 return;
1069
1070 // Now? Or later?
1071 eta = encodeManager.getNextLosslessRefresh(req);
1072 if (eta > 0) {
1073 losslessTimer.start(eta);
1074 return;
1075 }
1076 }
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001077
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001078 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001079
Pierre Ossman6b2f1132016-11-30 08:03:35 +01001080 if (!ui.is_empty())
1081 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001082 else {
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001083 int nextUpdate;
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001084
1085 // FIXME: If continuous updates aren't used then the client might
1086 // be slower than frameRate in its requests and we could
1087 // afford a larger update size
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001088 nextUpdate = server->msToNextUpdate();
1089 if (nextUpdate > 0) {
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001090 size_t bandwidth, maxUpdateSize;
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001091
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001092 // FIXME: Bandwidth estimation without congestion control
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001093 bandwidth = congestion.getBandwidth();
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001094
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001095 // FIXME: Hard coded value for maximum CPU throughput
1096 if (bandwidth > 5000000)
1097 bandwidth = 5000000;
1098
1099 maxUpdateSize = bandwidth * nextUpdate / 1000;
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001100 encodeManager.writeLosslessRefresh(req, server->getPixelBuffer(),
1101 cursor, maxUpdateSize);
1102 }
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001103 }
Pierre Ossman1b478e52011-11-15 12:08:30 +00001104
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001105 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001106
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001107 // The request might be for just part of the screen, so we cannot
1108 // just clear the entire update tracker.
1109 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001110
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001111 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001112}
1113
1114
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001115void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1116{
1117 if (!authenticated())
1118 return;
1119
Pierre Ossman6094ced2018-10-05 17:24:51 +02001120 cp.screenLayout = server->getScreenLayout();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001121
1122 if (state() != RFBSTATE_NORMAL)
1123 return;
1124
1125 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1126 cp.screenLayout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001127}
1128
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001129
1130// setCursor() is called whenever the cursor has changed shape or pixel format.
1131// If the client supports local cursor then it will arrange for the cursor to
1132// be sent to the client.
1133
1134void VNCSConnectionST::setCursor()
1135{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001136 if (state() != RFBSTATE_NORMAL)
1137 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001138
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001139 // We need to blank out the client's cursor or there will be two
Pierre Ossman25db44a2017-11-16 16:40:44 +01001140 if (needRenderedCursor()) {
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001141 cp.setCursor(emptyCursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001142 clientHasCursor = false;
1143 } else {
Pierre Ossman6094ced2018-10-05 17:24:51 +02001144 cp.setCursor(*server->getCursor());
Pierre Ossman25db44a2017-11-16 16:40:44 +01001145 clientHasCursor = true;
1146 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001147
Pierre Ossman8053c8e2017-02-21 12:59:04 +01001148 if (!writer()->writeSetCursorWithAlpha()) {
1149 if (!writer()->writeSetCursor()) {
1150 if (!writer()->writeSetXCursor()) {
1151 // No client support
1152 return;
1153 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001154 }
1155 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001156}
1157
1158void VNCSConnectionST::setDesktopName(const char *name)
1159{
1160 cp.setName(name);
1161
1162 if (state() != RFBSTATE_NORMAL)
1163 return;
1164
1165 if (!writer()->writeSetDesktopName()) {
1166 fprintf(stderr, "Client does not support desktop rename\n");
1167 return;
1168 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001169}
1170
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001171void VNCSConnectionST::setLEDState(unsigned int ledstate)
1172{
1173 if (state() != RFBSTATE_NORMAL)
1174 return;
1175
1176 cp.setLEDState(ledstate);
1177
Pierre Ossmanb218ecd2017-11-16 16:43:13 +01001178 writer()->writeLEDState();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001179}
1180
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001181void VNCSConnectionST::setSocketTimeouts()
1182{
1183 int timeoutms = rfb::Server::clientWaitTimeMillis;
1184 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1185 if (timeoutms == 0)
1186 timeoutms = -1;
1187 sock->inStream().setTimeout(timeoutms);
1188 sock->outStream().setTimeout(timeoutms);
1189}
1190
1191char* VNCSConnectionST::getStartTime()
1192{
1193 char* result = ctime(&startTime);
1194 result[24] = '\0';
1195 return result;
1196}
1197
1198void VNCSConnectionST::setStatus(int status)
1199{
1200 switch (status) {
1201 case 0:
1202 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1203 break;
1204 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001205 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001206 break;
1207 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001208 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001209 break;
1210 }
Pierre Ossman6094ced2018-10-05 17:24:51 +02001211 framebufferUpdateRequest(server->getPixelBuffer()->getRect(), false);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001212}
1213int VNCSConnectionST::getStatus()
1214{
1215 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1216 return 0;
1217 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1218 return 1;
1219 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1220 return 2;
1221 return 4;
1222}
1223