blob: d936573df388e843d3da1ec5593c2a480f10bc5e [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),
Pierre Ossmana114c342018-06-18 16:29:55 +020052 losslessTimer(this), server(server_),
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 Ossman2daba9b2018-10-29 10:03:37 +0100219 if (!client.supportsDesktopSize()) {
220 close("Client does not support desktop resize");
221 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000222 }
Pierre Ossman2daba9b2018-10-29 10:03:37 +0100223 writer()->writeDesktopSize(reasonServer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000224 }
Pierre Ossman6b2f1132016-11-30 08:03:35 +0100225
226 // Drop any lossy tracking that is now outside the framebuffer
227 encodeManager.pruneLosslessRefresh(Region(server->pb->getRect()));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000228 }
229 // Just update the whole screen at the moment because we're too lazy to
230 // work out what's actually changed.
231 updates.clear();
232 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000233 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000234 } catch(rdr::Exception &e) {
235 close(e.str());
236 }
237}
238
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000239void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000240{
241 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000242 writeFramebufferUpdate();
243 } catch(rdr::Exception &e) {
244 close(e.str());
245 }
246}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000247
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000248void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
249{
250 try {
251 screenLayoutChange(reason);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100252 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000253 } catch(rdr::Exception &e) {
254 close(e.str());
255 }
256}
257
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000258void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000259{
260 try {
261 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
262 } catch(rdr::Exception& e) {
263 close(e.str());
264 }
265}
266
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000267void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000268{
269 try {
270 if (!(accessRights & AccessCutText)) return;
271 if (!rfb::Server::sendCutText) return;
272 if (state() == RFBSTATE_NORMAL)
273 writer()->writeServerCutText(str, len);
274 } catch(rdr::Exception& e) {
275 close(e.str());
276 }
277}
278
Peter Åstrandc39e0782009-01-15 12:21:42 +0000279
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000280void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Åstrandc39e0782009-01-15 12:21:42 +0000281{
Peter Åstrandc39e0782009-01-15 12:21:42 +0000282 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000283 setDesktopName(name);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100284 writeFramebufferUpdate();
Peter Åstrandc39e0782009-01-15 12:21:42 +0000285 } catch(rdr::Exception& e) {
286 close(e.str());
287 }
288}
289
290
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000291void VNCSConnectionST::setCursorOrClose()
292{
293 try {
294 setCursor();
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100295 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000296 } catch(rdr::Exception& e) {
297 close(e.str());
298 }
299}
300
301
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100302void VNCSConnectionST::setLEDStateOrClose(unsigned int state)
303{
304 try {
305 setLEDState(state);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100306 writeFramebufferUpdate();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100307 } catch(rdr::Exception& e) {
308 close(e.str());
309 }
310}
311
312
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000313int VNCSConnectionST::checkIdleTimeout()
314{
315 int idleTimeout = rfb::Server::idleTimeout;
316 if (idleTimeout == 0) return 0;
317 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
318 idleTimeout = 15; // minimum of 15 seconds while authenticating
319 time_t now = time(0);
320 if (now < lastEventTime) {
321 // Someone must have set the time backwards. Set lastEventTime so that the
322 // idleTimeout will count from now.
323 vlog.info("Time has gone backwards - resetting idle timeout");
324 lastEventTime = now;
325 }
326 int timeLeft = lastEventTime + idleTimeout - now;
327 if (timeLeft < -60) {
328 // Our callback is over a minute late - someone must have set the time
329 // forwards. Set lastEventTime so that the idleTimeout will count from
330 // now.
331 vlog.info("Time has gone forwards - resetting idle timeout");
332 lastEventTime = now;
333 return secsToMillis(idleTimeout);
334 }
335 if (timeLeft <= 0) {
336 close("Idle timeout");
337 return 0;
338 }
339 return secsToMillis(timeLeft);
340}
341
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000342
343bool VNCSConnectionST::getComparerState()
344{
345 // We interpret a low compression level as an indication that the client
346 // wants to prioritise CPU usage over bandwidth, and hence disable the
347 // comparing update tracker.
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200348 return (client.compressLevel == -1) || (client.compressLevel > 1);
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000349}
350
351
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000352// renderedCursorChange() is called whenever the server-side rendered cursor
353// changes shape or position. It ensures that the next update will clean up
354// the old rendered cursor and if necessary draw the new rendered cursor.
355
356void VNCSConnectionST::renderedCursorChange()
357{
358 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200359 // Are we switching between client-side and server-side cursor?
Pierre Ossman25db44a2017-11-16 16:40:44 +0100360 if (clientHasCursor == needRenderedCursor())
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200361 setCursorOrClose();
Pierre Ossman25db44a2017-11-16 16:40:44 +0100362 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
Pierre Ossman330ca422017-11-06 13:15:55 +0100363 if (hasRenderedCursor)
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000364 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000365 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200366 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000367 writeFramebufferUpdateOrClose();
368 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000369}
370
371// needRenderedCursor() returns true if this client needs the server-side
372// rendered cursor. This may be because it does not support local cursor or
373// because the current cursor position has not been set by this client.
374// Unfortunately we can't know for sure when the current cursor position has
375// been set by this client. We guess that this is the case when the current
376// cursor position is the same as the last pointer event from this client, or
377// if it is a very short time since this client's last pointer event (up to a
378// second). [ Ideally we should do finer-grained timing here and make the time
379// configurable, but I don't think it's that important. ]
380
381bool VNCSConnectionST::needRenderedCursor()
382{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100383 if (state() != RFBSTATE_NORMAL)
384 return false;
385
Pierre Ossmanb114f5c2018-06-18 16:34:16 +0200386 if (!client.supportsLocalCursor())
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100387 return true;
388 if (!server->cursorPos.equals(pointerEventPos) &&
389 (time(0) - pointerEventTime) > 0)
390 return true;
391
392 return false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000393}
394
395
396void VNCSConnectionST::approveConnectionOrClose(bool accept,
397 const char* reason)
398{
399 try {
400 approveConnection(accept, reason);
401 } catch (rdr::Exception& e) {
402 close(e.str());
403 }
404}
405
406
407
408// -=- Callbacks from SConnection
409
410void VNCSConnectionST::authSuccess()
411{
412 lastEventTime = time(0);
413
414 server->startDesktop();
415
416 // - Set the connection parameters appropriately
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200417 client.setDimensions(server->pb->width(), server->pb->height(),
418 server->screenLayout);
419 client.setName(server->getName());
420 client.setLEDState(server->ledState);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000421
422 // - Set the default pixel format
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200423 client.setPF(server->pb->getPF());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000424 char buffer[256];
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200425 client.pf().print(buffer, 256);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000426 vlog.info("Server default pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000427
428 // - Mark the entire display as "dirty"
429 updates.add_changed(server->pb->getRect());
430 startTime = time(0);
431}
432
433void VNCSConnectionST::queryConnection(const char* userName)
434{
435 // - Authentication succeeded - clear from blacklist
436 CharArray name; name.buf = sock->getPeerAddress();
437 server->blHosts->clearBlackmark(name.buf);
438
439 // - Special case to provide a more useful error message
440 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
441 server->authClientCount() > 0) {
442 approveConnection(false, "The server is already in use");
443 return;
444 }
445
446 // - Does the client have the right to bypass the query?
447 if (reverseConnection ||
448 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
449 (accessRights & AccessNoQuery))
450 {
451 approveConnection(true);
452 return;
453 }
454
455 // - Get the server to display an Accept/Reject dialog, if required
456 // If a dialog is displayed, the result will be PENDING, and the
457 // server will call approveConnection at a later time
458 CharArray reason;
459 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
460 &reason.buf);
Pierre Ossman36304752017-10-04 16:21:57 +0200461 if (qr == VNCServerST::PENDING)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000462 return;
463
464 // - If server returns ACCEPT/REJECT then pass result to SConnection
465 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
466}
467
468void VNCSConnectionST::clientInit(bool shared)
469{
470 lastEventTime = time(0);
471 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100472 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000473 if (rfb::Server::neverShared) shared = false;
474 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100475 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000476 // - Close all the other connected clients
477 vlog.debug("non-shared connection - closing clients");
478 server->closeClients("Non-shared connection requested", getSock());
479 } else {
480 // - Refuse this connection if there are existing clients, in addition to
481 // this one
482 if (server->authClientCount() > 1) {
483 close("Server is already in use");
484 return;
485 }
486 }
487 }
488 SConnection::clientInit(shared);
489}
490
491void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
492{
493 SConnection::setPixelFormat(pf);
494 char buffer[256];
495 pf.print(buffer, 256);
496 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000497 setCursor();
498}
499
500void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
501{
502 pointerEventTime = lastEventTime = time(0);
503 server->lastUserInputTime = lastEventTime;
504 if (!(accessRights & AccessPtrEvents)) return;
505 if (!rfb::Server::acceptPointerEvents) return;
506 if (!server->pointerClient || server->pointerClient == this) {
507 pointerEventPos = pos;
508 if (buttonMask)
509 server->pointerClient = this;
510 else
511 server->pointerClient = 0;
512 server->desktop->pointerEvent(pointerEventPos, buttonMask);
513 }
514}
515
516
517class VNCSConnectionSTShiftPresser {
518public:
519 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
520 : desktop(desktop_), pressed(false) {}
521 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200522 if (pressed) {
523 vlog.debug("Releasing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200524 desktop->keyEvent(XK_Shift_L, 0, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200525 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000526 }
527 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200528 vlog.debug("Pressing fake Shift_L");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200529 desktop->keyEvent(XK_Shift_L, 0, true);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000530 pressed = true;
531 }
532 SDesktop* desktop;
533 bool pressed;
534};
535
536// keyEvent() - record in the pressedKeys which keys were pressed. Allow
537// multiple down events (for autorepeat), but only allow a single up event.
Pierre Ossman5ae28212017-05-16 14:30:38 +0200538void VNCSConnectionST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200539 rdr::U32 lookup;
540
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000541 lastEventTime = time(0);
542 server->lastUserInputTime = lastEventTime;
543 if (!(accessRights & AccessKeyEvents)) return;
544 if (!rfb::Server::acceptKeyEvents) return;
545
Pierre Ossman9a153b02015-08-31 10:01:14 +0200546 if (down)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200547 vlog.debug("Key pressed: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200548 else
Pierre Ossman5ae28212017-05-16 14:30:38 +0200549 vlog.debug("Key released: 0x%x / 0x%x", keysym, keycode);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200550
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000551 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200552 if (server->keyRemapper) {
553 rdr::U32 newkey;
Pierre Ossman5ae28212017-05-16 14:30:38 +0200554 newkey = server->keyRemapper->remapKey(keysym);
555 if (newkey != keysym) {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200556 vlog.debug("Key remapped to 0x%x", newkey);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200557 keysym = newkey;
Pierre Ossman9a153b02015-08-31 10:01:14 +0200558 }
559 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000560
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100561 // Avoid lock keys if we don't know the server state
562 if ((server->ledState == ledUnknown) &&
Pierre Ossman5ae28212017-05-16 14:30:38 +0200563 ((keysym == XK_Caps_Lock) ||
564 (keysym == XK_Num_Lock) ||
565 (keysym == XK_Scroll_Lock))) {
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100566 vlog.debug("Ignoring lock key (e.g. caps lock)");
567 return;
568 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100569
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100570 // Lock key heuristics
571 // (only for clients that do not support the LED state extension)
Pierre Ossmanb114f5c2018-06-18 16:34:16 +0200572 if (!client.supportsLEDState()) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100573 // Always ignore ScrollLock as we don't have a heuristic
574 // for that
Pierre Ossman5ae28212017-05-16 14:30:38 +0200575 if (keysym == XK_Scroll_Lock) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100576 vlog.debug("Ignoring lock key (e.g. caps lock)");
577 return;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100578 }
579
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100580 if (down && (server->ledState != ledUnknown)) {
581 // CapsLock synchronisation heuristic
582 // (this assumes standard interaction between CapsLock the Shift
583 // keys and normal characters)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200584 if (((keysym >= XK_A) && (keysym <= XK_Z)) ||
585 ((keysym >= XK_a) && (keysym <= XK_z))) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100586 bool uppercase, shift, lock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100587
Pierre Ossman5ae28212017-05-16 14:30:38 +0200588 uppercase = (keysym >= XK_A) && (keysym <= XK_Z);
Pierre Ossman851e6802017-09-12 16:44:44 +0200589 shift = isShiftPressed();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100590 lock = server->ledState & ledCapsLock;
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100591
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100592 if (lock == (uppercase == shift)) {
593 vlog.debug("Inserting fake CapsLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200594 server->desktop->keyEvent(XK_Caps_Lock, 0, true);
595 server->desktop->keyEvent(XK_Caps_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100596 }
597 }
598
599 // NumLock synchronisation heuristic
600 // (this is more cautious because of the differences between Unix,
601 // Windows and macOS)
Pierre Ossman5ae28212017-05-16 14:30:38 +0200602 if (((keysym >= XK_KP_Home) && (keysym <= XK_KP_Delete)) ||
603 ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
604 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal)) {
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100605 bool number, shift, lock;
606
Pierre Ossman5ae28212017-05-16 14:30:38 +0200607 number = ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
608 (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal);
Pierre Ossman851e6802017-09-12 16:44:44 +0200609 shift = isShiftPressed();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100610 lock = server->ledState & ledNumLock;
611
612 if (shift) {
613 // We don't know the appropriate NumLock state for when Shift
614 // is pressed as it could be one of:
615 //
616 // a) A Unix client where Shift negates NumLock
617 //
618 // b) A Windows client where Shift only cancels NumLock
619 //
620 // c) A macOS client where Shift doesn't have any effect
621 //
622 } else if (lock == (number == shift)) {
623 vlog.debug("Inserting fake NumLock to get in sync with client");
Pierre Ossman5ae28212017-05-16 14:30:38 +0200624 server->desktop->keyEvent(XK_Num_Lock, 0, true);
625 server->desktop->keyEvent(XK_Num_Lock, 0, false);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100626 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100627 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000628 }
629 }
630
631 // Turn ISO_Left_Tab into shifted Tab.
632 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
Pierre Ossman5ae28212017-05-16 14:30:38 +0200633 if (keysym == XK_ISO_Left_Tab) {
Pierre Ossman851e6802017-09-12 16:44:44 +0200634 if (!isShiftPressed())
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000635 shiftPresser.press();
Pierre Ossman5ae28212017-05-16 14:30:38 +0200636 keysym = XK_Tab;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000637 }
638
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200639 // We need to be able to track keys, so generate a fake index when we
640 // aren't given a keycode
641 if (keycode == 0)
642 lookup = 0x80000000 | keysym;
643 else
644 lookup = keycode;
645
646 // We force the same keysym for an already down key for the
647 // sake of sanity
648 if (pressedKeys.find(lookup) != pressedKeys.end())
649 keysym = pressedKeys[lookup];
650
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000651 if (down) {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200652 pressedKeys[lookup] = keysym;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000653 } else {
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200654 if (!pressedKeys.erase(lookup))
Pierre Ossman5ae28212017-05-16 14:30:38 +0200655 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000656 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +0200657
Pierre Ossman5ae28212017-05-16 14:30:38 +0200658 server->desktop->keyEvent(keysym, keycode, down);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000659}
660
661void VNCSConnectionST::clientCutText(const char* str, int len)
662{
663 if (!(accessRights & AccessCutText)) return;
664 if (!rfb::Server::acceptCutText) return;
665 server->desktop->clientCutText(str, len);
666}
667
668void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
669{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000670 Rect safeRect;
671
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000672 if (!(accessRights & AccessView)) return;
673
674 SConnection::framebufferUpdateRequest(r, incremental);
675
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000676 // Check that the client isn't sending crappy requests
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200677 if (!r.enclosed_by(Rect(0, 0, client.width(), client.height()))) {
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000678 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
Pierre Ossman9312b0e2018-06-20 12:25:14 +0200679 r.width(), r.height(), r.tl.x, r.tl.y,
Pierre Ossman0d3ce872018-06-18 15:59:00 +0200680 client.width(), client.height());
681 safeRect = r.intersect(Rect(0, 0, client.width(), client.height()));
Pierre Ossmane9962f72009-04-23 12:31:42 +0000682 } else {
683 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000684 }
685
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000686 // Just update the requested region.
687 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000688 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000689 if (!incremental || !continuousUpdates)
690 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000691
692 if (!incremental) {
693 // Non-incremental update - treat as if area requested has changed
694 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000695
696 // And send the screen layout to the client (which, unlike the
697 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossman2daba9b2018-10-29 10:03:37 +0100698 if (client.supportsEncoding(pseudoEncodingExtendedDesktopSize))
699 writer()->writeDesktopSize(reasonServer);
Pierre Ossman53125a72009-04-22 15:37:51 +0000700
701 // We do not send a DesktopSize since it only contains the
702 // framebuffer size (which the client already should know) and
703 // because some clients don't handle extra DesktopSize events
704 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000705 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000706}
707
Pierre Ossman34bb0612009-03-21 21:16:14 +0000708void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
709 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000710{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000711 unsigned int result;
712
Michal Srbb318b8f2014-11-24 13:18:28 +0200713 if (!(accessRights & AccessSetDesktopSize)) return;
714 if (!rfb::Server::acceptSetDesktopSize) return;
715
Pierre Ossman04e62db2009-03-23 16:57:07 +0000716 // Don't bother the desktop with an invalid configuration
717 if (!layout.validate(fb_width, fb_height)) {
Pierre Ossman2daba9b2018-10-29 10:03:37 +0100718 writer()->writeDesktopSize(reasonClient, resultInvalid);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000719 return;
720 }
721
722 // FIXME: the desktop will call back to VNCServerST and an extra set
723 // of ExtendedDesktopSize messages will be sent. This is okay
724 // protocol-wise, but unnecessary.
725 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
726
Pierre Ossman2daba9b2018-10-29 10:03:37 +0100727 writer()->writeDesktopSize(reasonClient, result);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000728
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000729 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000730 if (result == resultSuccess) {
731 if (server->screenLayout != layout)
732 throw Exception("Desktop configured a different screen layout than requested");
733 server->notifyScreenLayoutChange(this);
734 }
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000735}
736
Pierre Ossman2c764942011-11-14 15:54:30 +0000737void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
738{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100739 rdr::U8 type;
740
Pierre Ossman2c764942011-11-14 15:54:30 +0000741 if (flags & fenceFlagRequest) {
742 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000743 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000744
745 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
746 fenceDataLen = len;
747 delete [] fenceData;
Michal Srbf3afa242017-03-27 19:02:15 +0300748 fenceData = NULL;
Pierre Ossman2c764942011-11-14 15:54:30 +0000749 if (len > 0) {
750 fenceData = new char[len];
751 memcpy(fenceData, data, len);
752 }
753
754 return;
755 }
756
757 // We handle everything synchronously so we trivially honor these modes
758 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
759
760 writer()->writeFence(flags, len, data);
761 return;
762 }
763
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100764 if (len < 1)
765 vlog.error("Fence response of unexpected size received");
Pierre Ossman1b478e52011-11-15 12:08:30 +0000766
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100767 type = data[0];
768
769 switch (type) {
Pierre Ossman2c764942011-11-14 15:54:30 +0000770 case 0:
771 // Initial dummy fence;
772 break;
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100773 case 1:
Pierre Ossmanc09e5582015-12-11 20:23:17 +0100774 congestion.gotPong();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000775 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000776 default:
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100777 vlog.error("Fence response of unexpected type received");
Pierre Ossman2c764942011-11-14 15:54:30 +0000778 }
779}
780
Pierre Ossman1b478e52011-11-15 12:08:30 +0000781void VNCSConnectionST::enableContinuousUpdates(bool enable,
782 int x, int y, int w, int h)
783{
784 Rect rect;
785
Pierre Ossmanb114f5c2018-06-18 16:34:16 +0200786 if (!client.supportsFence() || !client.supportsContinuousUpdates())
Pierre Ossman1b478e52011-11-15 12:08:30 +0000787 throw Exception("Client tried to enable continuous updates when not allowed");
788
789 continuousUpdates = enable;
790
791 rect.setXYWH(x, y, w, h);
792 cuRegion.reset(rect);
793
794 if (enable) {
795 requested.clear();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000796 } else {
797 writer()->writeEndOfContinuousUpdates();
798 }
799}
800
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000801// supportsLocalCursor() is called whenever the status of
Pierre Ossmanb114f5c2018-06-18 16:34:16 +0200802// client.supportsLocalCursor() has changed. If the client does now support local
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000803// cursor, we make sure that the old server-side rendered cursor is cleaned up
804// and the cursor is sent to the client.
805
806void VNCSConnectionST::supportsLocalCursor()
807{
Pierre Ossman387a4172017-11-16 16:44:36 +0100808 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
809 if (hasRenderedCursor && !needRenderedCursor())
810 removeRenderedCursor = true;
811 setCursor();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000812}
813
Pierre Ossman2c764942011-11-14 15:54:30 +0000814void VNCSConnectionST::supportsFence()
815{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100816 char type = 0;
817 writer()->writeFence(fenceFlagRequest, sizeof(type), &type);
Pierre Ossman2c764942011-11-14 15:54:30 +0000818}
819
Pierre Ossman1b478e52011-11-15 12:08:30 +0000820void VNCSConnectionST::supportsContinuousUpdates()
821{
822 // We refuse to use continuous updates if we cannot monitor the buffer
823 // usage using fences.
Pierre Ossmanb114f5c2018-06-18 16:34:16 +0200824 if (!client.supportsFence())
Pierre Ossman1b478e52011-11-15 12:08:30 +0000825 return;
826
827 writer()->writeEndOfContinuousUpdates();
828}
829
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100830void VNCSConnectionST::supportsLEDState()
831{
832 writer()->writeLEDState();
833}
834
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000835
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000836bool VNCSConnectionST::handleTimeout(Timer* t)
837{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000838 try {
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +0200839 if ((t == &congestionTimer) ||
840 (t == &losslessTimer))
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100841 writeFramebufferUpdate();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000842 } catch (rdr::Exception& e) {
843 close(e.str());
844 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000845
846 return false;
847}
848
Pierre Ossman851e6802017-09-12 16:44:44 +0200849bool VNCSConnectionST::isShiftPressed()
850{
851 std::map<rdr::U32, rdr::U32>::const_iterator iter;
852
853 for (iter = pressedKeys.begin(); iter != pressedKeys.end(); ++iter) {
854 if (iter->second == XK_Shift_L)
855 return true;
856 if (iter->second == XK_Shift_R)
857 return true;
858 }
859
860 return false;
861}
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000862
Pierre Ossman1b478e52011-11-15 12:08:30 +0000863void VNCSConnectionST::writeRTTPing()
864{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100865 char type;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000866
Pierre Ossmanb114f5c2018-06-18 16:34:16 +0200867 if (!client.supportsFence())
Pierre Ossman1b478e52011-11-15 12:08:30 +0000868 return;
869
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100870 congestion.updatePosition(sock->outStream().length());
Pierre Ossman1b478e52011-11-15 12:08:30 +0000871
872 // We need to make sure any old update are already processed by the
873 // time we get the response back. This allows us to reliably throttle
874 // back on client overload, as well as network overload.
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100875 type = 1;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000876 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100877 sizeof(type), &type);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000878
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100879 congestion.sentPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000880}
881
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000882bool VNCSConnectionST::isCongested()
883{
Pierre Ossmance261812018-07-17 15:01:53 +0200884 int eta;
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100885
886 congestionTimer.stop();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000887
888 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200889 sock->outStream().flush();
Pierre Ossman8cf71632016-03-11 09:38:08 +0100890 congestion.debugTrace("congestion-trace.csv", sock->getFd());
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000891 if (sock->outStream().bufferUsage() > 0)
892 return true;
893
Pierre Ossmanb114f5c2018-06-18 16:34:16 +0200894 if (!client.supportsFence())
Pierre Ossman1b478e52011-11-15 12:08:30 +0000895 return false;
896
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100897 congestion.updatePosition(sock->outStream().length());
898 if (!congestion.isCongested())
Pierre Ossman1b478e52011-11-15 12:08:30 +0000899 return false;
900
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100901 eta = congestion.getUncongestedETA();
902 if (eta >= 0)
903 congestionTimer.start(eta);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000904
905 return true;
906}
907
908
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000909void VNCSConnectionST::writeFramebufferUpdate()
910{
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100911 congestion.updatePosition(sock->outStream().length());
912
Pierre Ossman2c764942011-11-14 15:54:30 +0000913 // We're in the middle of processing a command that's supposed to be
914 // synchronised. Allowing an update to slip out right now might violate
915 // that synchronisation.
916 if (syncFence)
917 return;
918
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000919 // We try to aggregate responses, so don't send out anything whilst we
920 // still have incoming messages. processMessages() will give us another
921 // chance to run once things are idle.
922 if (inProcessMessages)
923 return;
924
Pierre Ossman1b478e52011-11-15 12:08:30 +0000925 if (state() != RFBSTATE_NORMAL)
926 return;
927 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000928 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000929
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000930 // Check that we actually have some space on the link and retry in a
931 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +0200932 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000933 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000934
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100935 // Updates often consists of many small writes, and in continuous
936 // mode, we will also have small fence messages around the update. We
937 // need to aggregate these in order to not clog up TCP's congestion
938 // window.
Peter Åstrand (astrand)01dc1a62017-10-10 12:56:04 +0200939 sock->cork(true);
Pierre Ossman36dadf82011-11-15 12:11:32 +0000940
Pierre Ossmane9962f72009-04-23 12:31:42 +0000941 // First take care of any updates that cannot contain framebuffer data
942 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100943 writeNoDataUpdate();
944
945 // Then real data (if possible)
946 writeDataUpdate();
947
Peter Åstrand (astrand)01dc1a62017-10-10 12:56:04 +0200948 sock->cork(false);
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100949
950 congestion.updatePosition(sock->outStream().length());
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100951}
952
953void VNCSConnectionST::writeNoDataUpdate()
954{
955 if (!writer()->needNoDataUpdate())
956 return;
957
958 writer()->writeNoDataUpdate();
959
960 // Make sure no data update is sent until next request
961 requested.clear();
962}
963
964void VNCSConnectionST::writeDataUpdate()
965{
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100966 Region req, pending;
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100967 UpdateInfo ui;
968 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +0100969 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000970
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100971 // See what the client has requested (if anything)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000972 if (continuousUpdates)
973 req = cuRegion.union_(requested);
974 else
975 req = requested;
976
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100977 if (req.is_empty())
978 return;
979
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100980 // Get any framebuffer changes we haven't yet been informed of
981 pending = server->getPendingRegion();
982
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100983 // Get the lists of updates. Prior to exporting the data to the `ui' object,
984 // getUpdateInfo() will normalize the `updates' object such way that its
985 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +0000986 updates.getUpdateInfo(&ui, req);
987 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000988
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000989 // If the previous position of the rendered cursor overlaps the source of the
990 // copy, then when the copy happens the corresponding rectangle in the
991 // destination will be wrong, so add it to the changed region.
992
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200993 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
994 Region bogusCopiedCursor;
995
Pierre Ossman74385d32018-03-22 16:00:18 +0100996 bogusCopiedCursor = damagedCursorRegion;
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200997 bogusCopiedCursor.translate(ui.copy_delta);
998 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000999 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001000 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001001 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001002 }
1003 }
1004
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001005 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001006 // the changed region.
1007
1008 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001009 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001010 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001011 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001012 removeRenderedCursor = false;
1013 }
1014
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001015 // If we need a full cursor update then make sure its entire region
1016 // is marked as changed.
1017
1018 if (updateRenderedCursor) {
1019 updates.add_changed(server->getRenderedCursor()->getEffectiveRect());
1020 needNewUpdateInfo = true;
1021 updateRenderedCursor = false;
1022 }
1023
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001024 // The `updates' object could change, make sure we have valid update info.
1025
1026 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001027 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001028
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001029 // If there are queued updates then we cannot safely send an update
1030 // without risking a partially updated screen
1031
1032 if (!pending.is_empty()) {
1033 // However we might still be able to send a lossless refresh
1034 req.assign_subtract(pending);
1035 req.assign_subtract(ui.changed);
1036 req.assign_subtract(ui.copied);
1037
1038 ui.changed.clear();
1039 ui.copied.clear();
1040 }
1041
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001042 // Does the client need a server-side rendered cursor?
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001043
Pierre Ossman24684e52016-12-05 16:58:19 +01001044 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001045 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001046 Rect renderedCursorRect;
1047
Pierre Ossman24684e52016-12-05 16:58:19 +01001048 cursor = server->getRenderedCursor();
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001049 renderedCursorRect = cursor->getEffectiveRect();
Pierre Ossman24684e52016-12-05 16:58:19 +01001050
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001051 // Check that we don't try to copy over the cursor area, and
1052 // if that happens we need to treat it as changed so that we can
1053 // re-render it
1054 if (!ui.copied.intersect(renderedCursorRect).is_empty()) {
1055 ui.changed.assign_union(ui.copied.intersect(renderedCursorRect));
1056 ui.copied.assign_subtract(renderedCursorRect);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001057 }
1058
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001059 // Track where we've rendered the cursor
1060 damagedCursorRegion.assign_union(ui.changed.intersect(renderedCursorRect));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001061 }
1062
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001063 // Return if there is nothing to send the client.
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +02001064 if (ui.is_empty() && !writer()->needFakeUpdate()) {
1065 int eta;
Pierre Ossman8efc7b42018-03-23 11:45:51 +01001066
Peter Åstrand (astrand)7a368c92018-09-19 12:45:17 +02001067 // Any lossless refresh that needs handling?
1068 if (!encodeManager.needsLosslessRefresh(req))
1069 return;
1070
1071 // Now? Or later?
1072 eta = encodeManager.getNextLosslessRefresh(req);
1073 if (eta > 0) {
1074 losslessTimer.start(eta);
1075 return;
1076 }
1077 }
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001078
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001079 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001080
Pierre Ossman6b2f1132016-11-30 08:03:35 +01001081 if (!ui.is_empty())
1082 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001083 else {
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001084 int nextUpdate;
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001085
1086 // FIXME: If continuous updates aren't used then the client might
1087 // be slower than frameRate in its requests and we could
1088 // afford a larger update size
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001089 nextUpdate = server->msToNextUpdate();
1090 if (nextUpdate > 0) {
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001091 size_t bandwidth, maxUpdateSize;
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001092
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001093 // FIXME: Bandwidth estimation without congestion control
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001094 bandwidth = congestion.getBandwidth();
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001095
Pierre Ossmancb5a3992018-09-19 16:35:40 +02001096 // FIXME: Hard coded value for maximum CPU throughput
1097 if (bandwidth > 5000000)
1098 bandwidth = 5000000;
1099
1100 maxUpdateSize = bandwidth * nextUpdate / 1000;
Pierre Ossmanc3ce5ce2018-09-19 16:31:18 +02001101 encodeManager.writeLosslessRefresh(req, server->getPixelBuffer(),
1102 cursor, maxUpdateSize);
1103 }
Pierre Ossmana2b80d62018-03-23 09:30:09 +01001104 }
Pierre Ossman1b478e52011-11-15 12:08:30 +00001105
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001106 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001107
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001108 // The request might be for just part of the screen, so we cannot
1109 // just clear the entire update tracker.
1110 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001111
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001112 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001113}
1114
1115
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001116void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1117{
1118 if (!authenticated())
1119 return;
1120
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001121 client.setDimensions(client.width(), client.height(),
1122 server->screenLayout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001123
1124 if (state() != RFBSTATE_NORMAL)
1125 return;
1126
Pierre Ossman2daba9b2018-10-29 10:03:37 +01001127 writer()->writeDesktopSize(reason);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001128}
1129
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001130
1131// setCursor() is called whenever the cursor has changed shape or pixel format.
1132// If the client supports local cursor then it will arrange for the cursor to
1133// be sent to the client.
1134
1135void VNCSConnectionST::setCursor()
1136{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001137 if (state() != RFBSTATE_NORMAL)
1138 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001139
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001140 // We need to blank out the client's cursor or there will be two
Pierre Ossman25db44a2017-11-16 16:40:44 +01001141 if (needRenderedCursor()) {
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001142 client.setCursor(emptyCursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001143 clientHasCursor = false;
1144 } else {
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001145 client.setCursor(*server->cursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001146 clientHasCursor = true;
1147 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001148
Pierre Ossman2daba9b2018-10-29 10:03:37 +01001149 if (client.supportsLocalCursor())
1150 writer()->writeCursor();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001151}
1152
1153void VNCSConnectionST::setDesktopName(const char *name)
1154{
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001155 client.setName(name);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001156
1157 if (state() != RFBSTATE_NORMAL)
1158 return;
1159
1160 if (!writer()->writeSetDesktopName()) {
1161 fprintf(stderr, "Client does not support desktop rename\n");
1162 return;
1163 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001164}
1165
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001166void VNCSConnectionST::setLEDState(unsigned int ledstate)
1167{
1168 if (state() != RFBSTATE_NORMAL)
1169 return;
1170
Pierre Ossman0d3ce872018-06-18 15:59:00 +02001171 client.setLEDState(ledstate);
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001172
Pierre Ossmanb218ecd2017-11-16 16:43:13 +01001173 writer()->writeLEDState();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001174}
1175
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001176void VNCSConnectionST::setSocketTimeouts()
1177{
1178 int timeoutms = rfb::Server::clientWaitTimeMillis;
1179 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1180 if (timeoutms == 0)
1181 timeoutms = -1;
1182 sock->inStream().setTimeout(timeoutms);
1183 sock->outStream().setTimeout(timeoutms);
1184}
1185
1186char* VNCSConnectionST::getStartTime()
1187{
1188 char* result = ctime(&startTime);
1189 result[24] = '\0';
1190 return result;
1191}
1192
1193void VNCSConnectionST::setStatus(int status)
1194{
1195 switch (status) {
1196 case 0:
1197 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1198 break;
1199 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001200 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001201 break;
1202 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001203 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001204 break;
1205 }
1206 framebufferUpdateRequest(server->pb->getRect(), false);
1207}
1208int VNCSConnectionST::getStatus()
1209{
1210 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1211 return 0;
1212 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1213 return 1;
1214 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1215 return 2;
1216 return 4;
1217}
1218