blob: f01b248c45b555614737bc71a86341e68b902d45 [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 Ossman0d3ce872018-06-18 15:59:00 +0200195 if (client.width() && client.height() &&
196 (server->pb->width() != client.width() ||
197 server->pb->height() != client.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 //
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200207 //if (server->pb->width() > client.width())
208 // updates.add_changed(Rect(client.width(), 0, server->pb->width(),
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000209 // server->pb->height()));
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200210 //if (server->pb->height() > client.height())
211 // updates.add_changed(Rect(0, client.height(), client.width(),
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000212 // server->pb->height()));
213
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200214 damagedCursorRegion.assign_intersect(server->pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000215
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200216 client.setDimensions(server->pb->width(), server->pb->height(),
217 server->screenLayout);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000218 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000219 // We should only send EDS to client asking for both
220 if (!writer()->writeExtendedDesktopSize()) {
221 if (!writer()->writeSetDesktopSize()) {
222 close("Client does not support desktop resize");
223 return;
224 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000225 }
226 }
Pierre Ossman6b2f1132016-11-30 08:03:35 +0100227
228 // Drop any lossy tracking that is now outside the framebuffer
229 encodeManager.pruneLosslessRefresh(Region(server->pb->getRect()));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000230 }
231 // Just update the whole screen at the moment because we're too lazy to
232 // work out what's actually changed.
233 updates.clear();
234 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000235 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000236 } catch(rdr::Exception &e) {
237 close(e.str());
238 }
239}
240
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000241void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000242{
243 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000244 writeFramebufferUpdate();
245 } catch(rdr::Exception &e) {
246 close(e.str());
247 }
248}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000249
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000250void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
251{
252 try {
253 screenLayoutChange(reason);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100254 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000255 } catch(rdr::Exception &e) {
256 close(e.str());
257 }
258}
259
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000260void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000261{
262 try {
263 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
264 } catch(rdr::Exception& e) {
265 close(e.str());
266 }
267}
268
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000269void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000270{
271 try {
272 if (!(accessRights & AccessCutText)) return;
273 if (!rfb::Server::sendCutText) return;
274 if (state() == RFBSTATE_NORMAL)
275 writer()->writeServerCutText(str, len);
276 } catch(rdr::Exception& e) {
277 close(e.str());
278 }
279}
280
Peter Åstrandc39e0782009-01-15 12:21:42 +0000281
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000282void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Åstrandc39e0782009-01-15 12:21:42 +0000283{
Peter Åstrandc39e0782009-01-15 12:21:42 +0000284 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000285 setDesktopName(name);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100286 writeFramebufferUpdate();
Peter Åstrandc39e0782009-01-15 12:21:42 +0000287 } catch(rdr::Exception& e) {
288 close(e.str());
289 }
290}
291
292
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000293void VNCSConnectionST::setCursorOrClose()
294{
295 try {
296 setCursor();
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100297 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000298 } catch(rdr::Exception& e) {
299 close(e.str());
300 }
301}
302
303
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100304void VNCSConnectionST::setLEDStateOrClose(unsigned int state)
305{
306 try {
307 setLEDState(state);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100308 writeFramebufferUpdate();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100309 } catch(rdr::Exception& e) {
310 close(e.str());
311 }
312}
313
314
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000315int VNCSConnectionST::checkIdleTimeout()
316{
317 int idleTimeout = rfb::Server::idleTimeout;
318 if (idleTimeout == 0) return 0;
319 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
320 idleTimeout = 15; // minimum of 15 seconds while authenticating
321 time_t now = time(0);
322 if (now < lastEventTime) {
323 // Someone must have set the time backwards. Set lastEventTime so that the
324 // idleTimeout will count from now.
325 vlog.info("Time has gone backwards - resetting idle timeout");
326 lastEventTime = now;
327 }
328 int timeLeft = lastEventTime + idleTimeout - now;
329 if (timeLeft < -60) {
330 // Our callback is over a minute late - someone must have set the time
331 // forwards. Set lastEventTime so that the idleTimeout will count from
332 // now.
333 vlog.info("Time has gone forwards - resetting idle timeout");
334 lastEventTime = now;
335 return secsToMillis(idleTimeout);
336 }
337 if (timeLeft <= 0) {
338 close("Idle timeout");
339 return 0;
340 }
341 return secsToMillis(timeLeft);
342}
343
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000344
345bool VNCSConnectionST::getComparerState()
346{
347 // We interpret a low compression level as an indication that the client
348 // wants to prioritise CPU usage over bandwidth, and hence disable the
349 // comparing update tracker.
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200350 return (client.compressLevel == -1) || (client.compressLevel > 1);
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000351}
352
353
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000354// renderedCursorChange() is called whenever the server-side rendered cursor
355// changes shape or position. It ensures that the next update will clean up
356// the old rendered cursor and if necessary draw the new rendered cursor.
357
358void VNCSConnectionST::renderedCursorChange()
359{
360 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200361 // Are we switching between client-side and server-side cursor?
Pierre Ossman25db44a2017-11-16 16:40:44 +0100362 if (clientHasCursor == needRenderedCursor())
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200363 setCursorOrClose();
Pierre Ossman25db44a2017-11-16 16:40:44 +0100364 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
Pierre Ossman330ca422017-11-06 13:15:55 +0100365 if (hasRenderedCursor)
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000366 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000367 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200368 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000369 writeFramebufferUpdateOrClose();
370 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000371}
372
373// needRenderedCursor() returns true if this client needs the server-side
374// rendered cursor. This may be because it does not support local cursor or
375// because the current cursor position has not been set by this client.
376// Unfortunately we can't know for sure when the current cursor position has
377// been set by this client. We guess that this is the case when the current
378// cursor position is the same as the last pointer event from this client, or
379// if it is a very short time since this client's last pointer event (up to a
380// second). [ Ideally we should do finer-grained timing here and make the time
381// configurable, but I don't think it's that important. ]
382
383bool VNCSConnectionST::needRenderedCursor()
384{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100385 if (state() != RFBSTATE_NORMAL)
386 return false;
387
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200388 if (!client.supportsLocalCursorWithAlpha &&
389 !client.supportsLocalCursor && !client.supportsLocalXCursor)
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100390 return true;
391 if (!server->cursorPos.equals(pointerEventPos) &&
392 (time(0) - pointerEventTime) > 0)
393 return true;
394
395 return false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000396}
397
398
399void VNCSConnectionST::approveConnectionOrClose(bool accept,
400 const char* reason)
401{
402 try {
403 approveConnection(accept, reason);
404 } catch (rdr::Exception& e) {
405 close(e.str());
406 }
407}
408
409
410
411// -=- Callbacks from SConnection
412
413void VNCSConnectionST::authSuccess()
414{
415 lastEventTime = time(0);
416
417 server->startDesktop();
418
419 // - Set the connection parameters appropriately
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200420 client.setDimensions(server->pb->width(), server->pb->height(),
421 server->screenLayout);
422 client.setName(server->getName());
423 client.setLEDState(server->ledState);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000424
425 // - Set the default pixel format
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200426 client.setPF(server->pb->getPF());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000427 char buffer[256];
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200428 client.pf().print(buffer, 256);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000429 vlog.info("Server default pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000430
431 // - Mark the entire display as "dirty"
432 updates.add_changed(server->pb->getRect());
433 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
442 // - Special case to provide a more useful error message
443 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
444 server->authClientCount() > 0) {
445 approveConnection(false, "The server is already in use");
446 return;
447 }
448
449 // - Does the client have the right to bypass the query?
450 if (reverseConnection ||
451 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
452 (accessRights & AccessNoQuery))
453 {
454 approveConnection(true);
455 return;
456 }
457
458 // - Get the server to display an Accept/Reject dialog, if required
459 // If a dialog is displayed, the result will be PENDING, and the
460 // server will call approveConnection at a later time
461 CharArray reason;
462 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
463 &reason.buf);
Pierre Ossman36304752017-10-04 16:21:57 +0200464 if (qr == VNCServerST::PENDING)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000465 return;
466
467 // - If server returns ACCEPT/REJECT then pass result to SConnection
468 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
469}
470
471void VNCSConnectionST::clientInit(bool shared)
472{
473 lastEventTime = time(0);
474 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100475 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000476 if (rfb::Server::neverShared) shared = false;
477 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100478 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000479 // - Close all the other connected clients
480 vlog.debug("non-shared connection - closing clients");
481 server->closeClients("Non-shared connection requested", getSock());
482 } else {
483 // - Refuse this connection if there are existing clients, in addition to
484 // this one
485 if (server->authClientCount() > 1) {
486 close("Server is already in use");
487 return;
488 }
489 }
490 }
491 SConnection::clientInit(shared);
492}
493
494void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
495{
496 SConnection::setPixelFormat(pf);
497 char buffer[256];
498 pf.print(buffer, 256);
499 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000500 setCursor();
501}
502
503void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
504{
505 pointerEventTime = lastEventTime = time(0);
506 server->lastUserInputTime = lastEventTime;
507 if (!(accessRights & AccessPtrEvents)) return;
508 if (!rfb::Server::acceptPointerEvents) return;
509 if (!server->pointerClient || server->pointerClient == this) {
510 pointerEventPos = pos;
511 if (buttonMask)
512 server->pointerClient = this;
513 else
514 server->pointerClient = 0;
515 server->desktop->pointerEvent(pointerEventPos, buttonMask);
516 }
517}
518
519
520class VNCSConnectionSTShiftPresser {
521public:
522 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
523 : desktop(desktop_), pressed(false) {}
524 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200525 if (pressed) {
526 vlog.debug("Releasing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200527 desktop->keyEvent(XK_Shift_L, 0, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200528 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000529 }
530 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200531 vlog.debug("Pressing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200532 desktop->keyEvent(XK_Shift_L, 0, true);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000533 pressed = true;
534 }
535 SDesktop* desktop;
536 bool pressed;
537};
538
539// keyEvent() - record in the pressedKeys which keys were pressed. Allow
540// multiple down events (for autorepeat), but only allow a single up event.
Pierre Ossman5ae28212017-05-16 14:30:38 +0200541void VNCSConnectionST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200542 rdr::U32 lookup;
543
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000544 lastEventTime = time(0);
545 server->lastUserInputTime = lastEventTime;
546 if (!(accessRights & AccessKeyEvents)) return;
547 if (!rfb::Server::acceptKeyEvents) return;
548
Pierre Ossman9a153b02015-08-31 10:01:14 +0200549 if (down)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200550 vlog.debug("Key pressed: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200551 else
Pierre Ossman5ae28212017-05-16 14:30:38 +0200552 vlog.debug("Key released: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200553
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000554 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200555 if (server->keyRemapper) {
556 rdr::U32 newkey;
Pierre Ossman5ae28212017-05-16 14:30:38 +0200557 newkey = server->keyRemapper->remapKey(keysym);
558 if (newkey != keysym) {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200559 vlog.debug("Key remapped to 0x%x", newkey);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200560 keysym = newkey;
Pierre Ossman9a153b02015-08-31 10:01:14 +0200561 }
562 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000563
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100564 // Avoid lock keys if we don't know the server state
565 if ((server->ledState == ledUnknown) &&
Pierre Ossman5ae28212017-05-16 14:30:38 +0200566 ((keysym == XK_Caps_Lock) ||
567 (keysym == XK_Num_Lock) ||
568 (keysym == XK_Scroll_Lock))) {
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100569 vlog.debug("Ignoring lock key (e.g. caps lock)");
570 return;
571 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100572
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100573 // Lock key heuristics
574 // (only for clients that do not support the LED state extension)
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200575 if (!client.supportsLEDState) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100576 // Always ignore ScrollLock as we don't have a heuristic
577 // for that
Pierre Ossman5ae28212017-05-16 14:30:38 +0200578 if (keysym == XK_Scroll_Lock) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100579 vlog.debug("Ignoring lock key (e.g. caps lock)");
580 return;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100581 }
582
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100583 if (down && (server->ledState != ledUnknown)) {
584 // CapsLock synchronisation heuristic
585 // (this assumes standard interaction between CapsLock the Shift
586 // keys and normal characters)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200587 if (((keysym >= XK_A) && (keysym <= XK_Z)) ||
588 ((keysym >= XK_a) && (keysym <= XK_z))) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100589 bool uppercase, shift, lock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100590
Pierre Ossman5ae28212017-05-16 14:30:38 +0200591 uppercase = (keysym >= XK_A) && (keysym <= XK_Z);
Pierre Ossman851e6802017-09-12 16:44:44 +0200592 shift = isShiftPressed();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100593 lock = server->ledState & ledCapsLock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100594
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100595 if (lock == (uppercase == shift)) {
596 vlog.debug("Inserting fake CapsLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200597 server->desktop->keyEvent(XK_Caps_Lock, 0, true);
598 server->desktop->keyEvent(XK_Caps_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100599 }
600 }
601
602 // NumLock synchronisation heuristic
603 // (this is more cautious because of the differences between Unix,
604 // Windows and macOS)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200605 if (((keysym >= XK_KP_Home) && (keysym <= XK_KP_Delete)) ||
606 ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
607 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal)) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100608 bool number, shift, lock;
609
Pierre Ossman5ae28212017-05-16 14:30:38 +0200610 number = ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
611 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal);
Pierre Ossman851e6802017-09-12 16:44:44 +0200612 shift = isShiftPressed();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100613 lock = server->ledState & ledNumLock;
614
615 if (shift) {
616 // We don't know the appropriate NumLock state for when Shift
617 // is pressed as it could be one of:
618 //
619 // a) A Unix client where Shift negates NumLock
620 //
621 // b) A Windows client where Shift only cancels NumLock
622 //
623 // c) A macOS client where Shift doesn't have any effect
624 //
625 } else if (lock == (number == shift)) {
626 vlog.debug("Inserting fake NumLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200627 server->desktop->keyEvent(XK_Num_Lock, 0, true);
628 server->desktop->keyEvent(XK_Num_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100629 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100630 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000631 }
632 }
633
634 // Turn ISO_Left_Tab into shifted Tab.
635 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200636 if (keysym == XK_ISO_Left_Tab) {
Pierre Ossman851e6802017-09-12 16:44:44 +0200637 if (!isShiftPressed())
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000638 shiftPresser.press();
Pierre Ossman5ae28212017-05-16 14:30:38 +0200639 keysym = XK_Tab;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000640 }
641
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200642 // We need to be able to track keys, so generate a fake index when we
643 // aren't given a keycode
644 if (keycode == 0)
645 lookup = 0x80000000 | keysym;
646 else
647 lookup = keycode;
648
649 // We force the same keysym for an already down key for the
650 // sake of sanity
651 if (pressedKeys.find(lookup) != pressedKeys.end())
652 keysym = pressedKeys[lookup];
653
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000654 if (down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200655 pressedKeys[lookup] = keysym;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000656 } else {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200657 if (!pressedKeys.erase(lookup))
Pierre Ossman5ae28212017-05-16 14:30:38 +0200658 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000659 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200660
Pierre Ossman5ae28212017-05-16 14:30:38 +0200661 server->desktop->keyEvent(keysym, keycode, down);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000662}
663
664void VNCSConnectionST::clientCutText(const char* str, int len)
665{
666 if (!(accessRights & AccessCutText)) return;
667 if (!rfb::Server::acceptCutText) return;
668 server->desktop->clientCutText(str, len);
669}
670
671void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
672{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000673 Rect safeRect;
674
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000675 if (!(accessRights & AccessView)) return;
676
677 SConnection::framebufferUpdateRequest(r, incremental);
678
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000679 // Check that the client isn't sending crappy requests
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200680 if (!r.enclosed_by(Rect(0, 0, client.width(), client.height()))) {
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000681 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
Pierre Ossman9312b0e2018-06-20 12:25:14 +0200682 r.width(), r.height(), r.tl.x, r.tl.y,
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200683 client.width(), client.height());
684 safeRect = r.intersect(Rect(0, 0, client.width(), client.height()));
Pierre Ossmane9962f72009-04-23 12:31:42 +0000685 } else {
686 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000687 }
688
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000689 // Just update the requested region.
690 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000691 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000692 if (!incremental || !continuousUpdates)
693 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000694
695 if (!incremental) {
696 // Non-incremental update - treat as if area requested has changed
697 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000698
699 // And send the screen layout to the client (which, unlike the
700 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000701 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000702
703 // We do not send a DesktopSize since it only contains the
704 // framebuffer size (which the client already should know) and
705 // because some clients don't handle extra DesktopSize events
706 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000707 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000708}
709
Pierre Ossman34bb0612009-03-21 21:16:14 +0000710void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
711 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000712{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000713 unsigned int result;
714
Michal Srbb318b8f2014-11-24 13:18:28 +0200715 if (!(accessRights & AccessSetDesktopSize)) return;
716 if (!rfb::Server::acceptSetDesktopSize) return;
717
Pierre Ossman04e62db2009-03-23 16:57:07 +0000718 // Don't bother the desktop with an invalid configuration
719 if (!layout.validate(fb_width, fb_height)) {
720 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
721 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000722 return;
723 }
724
725 // FIXME: the desktop will call back to VNCServerST and an extra set
726 // of ExtendedDesktopSize messages will be sent. This is okay
727 // protocol-wise, but unnecessary.
728 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
729
Pierre Ossman04e62db2009-03-23 16:57:07 +0000730 writer()->writeExtendedDesktopSize(reasonClient, result,
731 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000732
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000733 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000734 if (result == resultSuccess) {
735 if (server->screenLayout != layout)
736 throw Exception("Desktop configured a different screen layout than requested");
737 server->notifyScreenLayoutChange(this);
738 }
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000739}
740
Pierre Ossman2c764942011-11-14 15:54:30 +0000741void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
742{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100743 rdr::U8 type;
744
Pierre Ossman2c764942011-11-14 15:54:30 +0000745 if (flags & fenceFlagRequest) {
746 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000747 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000748
749 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
750 fenceDataLen = len;
751 delete [] fenceData;
Michal Srbf3afa242017-03-27 19:02:15 +0300752 fenceData = NULL;
Pierre Ossman2c764942011-11-14 15:54:30 +0000753 if (len > 0) {
754 fenceData = new char[len];
755 memcpy(fenceData, data, len);
756 }
757
758 return;
759 }
760
761 // We handle everything synchronously so we trivially honor these modes
762 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
763
764 writer()->writeFence(flags, len, data);
765 return;
766 }
767
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100768 if (len < 1)
769 vlog.error("Fence response of unexpected size received");
Pierre Ossman1b478e52011-11-15 12:08:30 +0000770
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100771 type = data[0];
772
773 switch (type) {
Pierre Ossman2c764942011-11-14 15:54:30 +0000774 case 0:
775 // Initial dummy fence;
776 break;
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100777 case 1:
Pierre Ossmanc09e5582015-12-11 20:23:17 +0100778 congestion.gotPong();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000779 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000780 default:
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100781 vlog.error("Fence response of unexpected type received");
Pierre Ossman2c764942011-11-14 15:54:30 +0000782 }
783}
784
Pierre Ossman1b478e52011-11-15 12:08:30 +0000785void VNCSConnectionST::enableContinuousUpdates(bool enable,
786 int x, int y, int w, int h)
787{
788 Rect rect;
789
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200790 if (!client.supportsFence || !client.supportsContinuousUpdates)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000791 throw Exception("Client tried to enable continuous updates when not allowed");
792
793 continuousUpdates = enable;
794
795 rect.setXYWH(x, y, w, h);
796 cuRegion.reset(rect);
797
798 if (enable) {
799 requested.clear();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000800 } else {
801 writer()->writeEndOfContinuousUpdates();
802 }
803}
804
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000805// supportsLocalCursor() is called whenever the status of
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200806// client.supportsLocalCursor has changed. If the client does now support local
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000807// cursor, we make sure that the old server-side rendered cursor is cleaned up
808// and the cursor is sent to the client.
809
810void VNCSConnectionST::supportsLocalCursor()
811{
Pierre Ossman387a4172017-11-16 16:44:36 +0100812 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
813 if (hasRenderedCursor && !needRenderedCursor())
814 removeRenderedCursor = true;
815 setCursor();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000816}
817
Pierre Ossman2c764942011-11-14 15:54:30 +0000818void VNCSConnectionST::supportsFence()
819{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100820 char type = 0;
821 writer()->writeFence(fenceFlagRequest, sizeof(type), &type);
Pierre Ossman2c764942011-11-14 15:54:30 +0000822}
823
Pierre Ossman1b478e52011-11-15 12:08:30 +0000824void VNCSConnectionST::supportsContinuousUpdates()
825{
826 // We refuse to use continuous updates if we cannot monitor the buffer
827 // usage using fences.
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200828 if (!client.supportsFence)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000829 return;
830
831 writer()->writeEndOfContinuousUpdates();
832}
833
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100834void VNCSConnectionST::supportsLEDState()
835{
836 writer()->writeLEDState();
837}
838
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000839
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000840bool VNCSConnectionST::handleTimeout(Timer* t)
841{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000842 try {
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +0200843 if ((t == &congestionTimer) ||
844 (t == &losslessTimer))
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100845 writeFramebufferUpdate();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000846 } catch (rdr::Exception& e) {
847 close(e.str());
848 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000849
850 return false;
851}
852
Pierre Ossman851e6802017-09-12 16:44:44 +0200853bool VNCSConnectionST::isShiftPressed()
854{
855 std::map<rdr::U32, rdr::U32>::const_iterator iter;
856
857 for (iter = pressedKeys.begin(); iter != pressedKeys.end(); ++iter) {
858 if (iter->second == XK_Shift_L)
859 return true;
860 if (iter->second == XK_Shift_R)
861 return true;
862 }
863
864 return false;
865}
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000866
Pierre Ossman1b478e52011-11-15 12:08:30 +0000867void VNCSConnectionST::writeRTTPing()
868{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100869 char type;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000870
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200871 if (!client.supportsFence)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000872 return;
873
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100874 congestion.updatePosition(sock->outStream().length());
Pierre Ossman1b478e52011-11-15 12:08:30 +0000875
876 // We need to make sure any old update are already processed by the
877 // time we get the response back. This allows us to reliably throttle
878 // back on client overload, as well as network overload.
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100879 type = 1;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000880 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100881 sizeof(type), &type);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000882
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100883 congestion.sentPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000884}
885
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000886bool VNCSConnectionST::isCongested()
887{
Pierre Ossmance261812018-07-17 15:01:53 +0200888 int eta;
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100889
890 congestionTimer.stop();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000891
892 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200893 sock->outStream().flush();
Pierre Ossman8cf71632016-03-11 09:38:08 +0100894 congestion.debugTrace("congestion-trace.csv", sock->getFd());
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000895 if (sock->outStream().bufferUsage() > 0)
896 return true;
897
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200898 if (!client.supportsFence)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000899 return false;
900
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100901 congestion.updatePosition(sock->outStream().length());
902 if (!congestion.isCongested())
Pierre Ossman1b478e52011-11-15 12:08:30 +0000903 return false;
904
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100905 eta = congestion.getUncongestedETA();
906 if (eta >= 0)
907 congestionTimer.start(eta);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000908
909 return true;
910}
911
912
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000913void VNCSConnectionST::writeFramebufferUpdate()
914{
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100915 congestion.updatePosition(sock->outStream().length());
916
Pierre Ossman2c764942011-11-14 15:54:30 +0000917 // We're in the middle of processing a command that's supposed to be
918 // synchronised. Allowing an update to slip out right now might violate
919 // that synchronisation.
920 if (syncFence)
921 return;
922
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000923 // We try to aggregate responses, so don't send out anything whilst we
924 // still have incoming messages. processMessages() will give us another
925 // chance to run once things are idle.
926 if (inProcessMessages)
927 return;
928
Pierre Ossman1b478e52011-11-15 12:08:30 +0000929 if (state() != RFBSTATE_NORMAL)
930 return;
931 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000932 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000933
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000934 // Check that we actually have some space on the link and retry in a
935 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +0200936 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000937 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000938
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100939 // Updates often consists of many small writes, and in continuous
940 // mode, we will also have small fence messages around the update. We
941 // need to aggregate these in order to not clog up TCP's congestion
942 // window.
Peter Åstrand (astrand)01dc1a62017-10-10 12:56:04 +0200943 sock->cork(true);
Pierre Ossman36dadf82011-11-15 12:11:32 +0000944
Pierre Ossmane9962f72009-04-23 12:31:42 +0000945 // First take care of any updates that cannot contain framebuffer data
946 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100947 writeNoDataUpdate();
948
949 // Then real data (if possible)
950 writeDataUpdate();
951
Peter Åstrand (astrand)01dc1a62017-10-10 12:56:04 +0200952 sock->cork(false);
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100953
954 congestion.updatePosition(sock->outStream().length());
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100955}
956
957void VNCSConnectionST::writeNoDataUpdate()
958{
959 if (!writer()->needNoDataUpdate())
960 return;
961
962 writer()->writeNoDataUpdate();
963
964 // Make sure no data update is sent until next request
965 requested.clear();
966}
967
968void VNCSConnectionST::writeDataUpdate()
969{
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100970 Region req, pending;
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100971 UpdateInfo ui;
972 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +0100973 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000974
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200975 updates.enable_copyrect(client.useCopyRect);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000976
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100977 // See what the client has requested (if anything)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000978 if (continuousUpdates)
979 req = cuRegion.union_(requested);
980 else
981 req = requested;
982
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100983 if (req.is_empty())
984 return;
985
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100986 // Get any framebuffer changes we haven't yet been informed of
987 pending = server->getPendingRegion();
988
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100989 // Get the lists of updates. Prior to exporting the data to the `ui' object,
990 // getUpdateInfo() will normalize the `updates' object such way that its
991 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +0000992 updates.getUpdateInfo(&ui, req);
993 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000994
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000995 // If the previous position of the rendered cursor overlaps the source of the
996 // copy, then when the copy happens the corresponding rectangle in the
997 // destination will be wrong, so add it to the changed region.
998
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200999 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
1000 Region bogusCopiedCursor;
1001
Pierre Ossman74385d32018-03-22 16:00:18 +01001002 bogusCopiedCursor = damagedCursorRegion;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001003 bogusCopiedCursor.translate(ui.copy_delta);
1004 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001005 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001006 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001007 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001008 }
1009 }
1010
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001011 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001012 // the changed region.
1013
1014 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001015 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001016 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001017 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001018 removeRenderedCursor = false;
1019 }
1020
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001021 // If we need a full cursor update then make sure its entire region
1022 // is marked as changed.
1023
1024 if (updateRenderedCursor) {
1025 updates.add_changed(server->getRenderedCursor()->getEffectiveRect());
1026 needNewUpdateInfo = true;
1027 updateRenderedCursor = false;
1028 }
1029
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001030 // The `updates' object could change, make sure we have valid update info.
1031
1032 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001033 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001034
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001035 // If there are queued updates then we cannot safely send an update
1036 // without risking a partially updated screen
1037
1038 if (!pending.is_empty()) {
1039 // However we might still be able to send a lossless refresh
1040 req.assign_subtract(pending);
1041 req.assign_subtract(ui.changed);
1042 req.assign_subtract(ui.copied);
1043
1044 ui.changed.clear();
1045 ui.copied.clear();
1046 }
1047
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001048 // Does the client need a server-side rendered cursor?
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001049
Pierre Ossman24684e52016-12-05 16:58:19 +01001050 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001051 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001052 Rect renderedCursorRect;
1053
Pierre Ossman24684e52016-12-05 16:58:19 +01001054 cursor = server->getRenderedCursor();
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001055 renderedCursorRect = cursor->getEffectiveRect();
Pierre Ossman24684e52016-12-05 16:58:19 +01001056
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001057 // Check that we don't try to copy over the cursor area, and
1058 // if that happens we need to treat it as changed so that we can
1059 // re-render it
1060 if (!ui.copied.intersect(renderedCursorRect).is_empty()) {
1061 ui.changed.assign_union(ui.copied.intersect(renderedCursorRect));
1062 ui.copied.assign_subtract(renderedCursorRect);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001063 }
1064
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001065 // Track where we've rendered the cursor
1066 damagedCursorRegion.assign_union(ui.changed.intersect(renderedCursorRect));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001067 }
1068
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001069 // Return if there is nothing to send the client.
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +02001070 if (ui.is_empty() && !writer()->needFakeUpdate()) {
1071 int eta;
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001072
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +02001073 // Any lossless refresh that needs handling?
1074 if (!encodeManager.needsLosslessRefresh(req))
1075 return;
1076
1077 // Now? Or later?
1078 eta = encodeManager.getNextLosslessRefresh(req);
1079 if (eta > 0) {
1080 losslessTimer.start(eta);
1081 return;
1082 }
1083 }
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001084
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001085 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001086
Pierre Ossman6b2f1132016-11-30 08:03:35 +01001087 if (!ui.is_empty())
1088 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001089 else {
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001090 int nextUpdate;
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001091
1092 // FIXME: If continuous updates aren't used then the client might
1093 // be slower than frameRate in its requests and we could
1094 // afford a larger update size
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001095 nextUpdate = server->msToNextUpdate();
1096 if (nextUpdate > 0) {
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001097 size_t bandwidth, maxUpdateSize;
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001098
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001099 // FIXME: Bandwidth estimation without congestion control
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001100 bandwidth = congestion.getBandwidth();
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001101
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001102 // FIXME: Hard coded value for maximum CPU throughput
1103 if (bandwidth > 5000000)
1104 bandwidth = 5000000;
1105
1106 maxUpdateSize = bandwidth * nextUpdate / 1000;
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001107 encodeManager.writeLosslessRefresh(req, server->getPixelBuffer(),
1108 cursor, maxUpdateSize);
1109 }
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001110 }
Pierre Ossman1b478e52011-11-15 12:08:30 +00001111
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001112 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001113
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001114 // The request might be for just part of the screen, so we cannot
1115 // just clear the entire update tracker.
1116 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001117
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001118 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001119}
1120
1121
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001122void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1123{
1124 if (!authenticated())
1125 return;
1126
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001127 client.setDimensions(client.width(), client.height(),
1128 server->screenLayout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001129
1130 if (state() != RFBSTATE_NORMAL)
1131 return;
1132
Pierre Ossman9312b0e2018-06-20 12:25:14 +02001133 writer()->writeExtendedDesktopSize(reason, 0,
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001134 client.width(), client.height(),
1135 client.screenLayout());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001136}
1137
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001138
1139// setCursor() is called whenever the cursor has changed shape or pixel format.
1140// If the client supports local cursor then it will arrange for the cursor to
1141// be sent to the client.
1142
1143void VNCSConnectionST::setCursor()
1144{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001145 if (state() != RFBSTATE_NORMAL)
1146 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001147
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001148 // We need to blank out the client's cursor or there will be two
Pierre Ossman25db44a2017-11-16 16:40:44 +01001149 if (needRenderedCursor()) {
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001150 client.setCursor(emptyCursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001151 clientHasCursor = false;
1152 } else {
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001153 client.setCursor(*server->cursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001154 clientHasCursor = true;
1155 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001156
Pierre Ossman8053c8e2017-02-21 12:59:04 +01001157 if (!writer()->writeSetCursorWithAlpha()) {
1158 if (!writer()->writeSetCursor()) {
1159 if (!writer()->writeSetXCursor()) {
1160 // No client support
1161 return;
1162 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001163 }
1164 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001165}
1166
1167void VNCSConnectionST::setDesktopName(const char *name)
1168{
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001169 client.setName(name);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001170
1171 if (state() != RFBSTATE_NORMAL)
1172 return;
1173
1174 if (!writer()->writeSetDesktopName()) {
1175 fprintf(stderr, "Client does not support desktop rename\n");
1176 return;
1177 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001178}
1179
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001180void VNCSConnectionST::setLEDState(unsigned int ledstate)
1181{
1182 if (state() != RFBSTATE_NORMAL)
1183 return;
1184
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001185 client.setLEDState(ledstate);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001186
Pierre Ossmanb218ecd2017-11-16 16:43:13 +01001187 writer()->writeLEDState();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001188}
1189
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001190void VNCSConnectionST::setSocketTimeouts()
1191{
1192 int timeoutms = rfb::Server::clientWaitTimeMillis;
1193 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1194 if (timeoutms == 0)
1195 timeoutms = -1;
1196 sock->inStream().setTimeout(timeoutms);
1197 sock->outStream().setTimeout(timeoutms);
1198}
1199
1200char* VNCSConnectionST::getStartTime()
1201{
1202 char* result = ctime(&startTime);
1203 result[24] = '\0';
1204 return result;
1205}
1206
1207void VNCSConnectionST::setStatus(int status)
1208{
1209 switch (status) {
1210 case 0:
1211 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1212 break;
1213 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001214 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001215 break;
1216 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001217 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001218 break;
1219 }
1220 framebufferUpdateRequest(server->pb->getRect(), false);
1221}
1222int VNCSConnectionST::getStatus()
1223{
1224 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1225 return 0;
1226 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1227 return 1;
1228 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1229 return 2;
1230 return 4;
1231}
1232