blob: 924f724b362308e40a261f10814f8a8e5850064e [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
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00003 *
4 * This is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This software is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this software; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17 * USA.
18 */
19
Pierre Ossmana830bec2011-11-08 12:12:02 +000020#include <network/TcpSocket.h>
Pierre Ossman707fa122015-12-11 20:21:20 +010021
22#include <rfb/ComparingUpdateTracker.h>
23#include <rfb/Encoder.h>
24#include <rfb/KeyRemapper.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000025#include <rfb/LogWriter.h>
Adam Tkac5a0caed2010-04-23 13:58:10 +000026#include <rfb/Security.h>
Pierre Ossman707fa122015-12-11 20:21:20 +010027#include <rfb/ServerCore.h>
28#include <rfb/SMsgWriter.h>
29#include <rfb/VNCServerST.h>
30#include <rfb/VNCSConnectionST.h>
Pierre Ossmanc5e25602009-03-20 12:59:05 +000031#include <rfb/screenTypes.h>
Pierre Ossman2c764942011-11-14 15:54:30 +000032#include <rfb/fenceTypes.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010033#include <rfb/ledStates.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010034#define XK_LATIN1
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000035#define XK_MISCELLANY
36#define XK_XKB_KEYS
37#include <rfb/keysymdef.h>
38
39using namespace rfb;
40
41static LogWriter vlog("VNCSConnST");
42
Pierre Ossman71ca8d52017-09-15 11:03:12 +020043static Cursor emptyCursor(0, 0, Point(0, 0), NULL);
44
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000045VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
46 bool reverse)
Pierre Ossman7069bdd2015-02-06 14:41:58 +010047 : sock(s), reverseConnection(reverse),
Pierre Ossman36304752017-10-04 16:21:57 +020048 inProcessMessages(false),
Pierre Ossmanb8b1e962012-07-20 10:47:00 +000049 pendingSyncFence(false), syncFence(false), fenceFlags(0),
Pierre Ossmana99d14d2015-12-13 15:43:46 +010050 fenceDataLen(0), fenceData(NULL), congestionTimer(this),
Pierre Ossman0c9bd4b2014-07-09 16:44:11 +020051 server(server_), updates(false),
Pierre Ossman671d2ef2015-06-09 16:09:06 +020052 updateRenderedCursor(false), removeRenderedCursor(false),
Pierre Ossmana40ab202016-04-29 15:35:56 +020053 continuousUpdates(false), encodeManager(this), pointerEventTime(0),
Pierre Ossman25db44a2017-11-16 16:40:44 +010054 clientHasCursor(false),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000055 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000056{
57 setStreams(&sock->inStream(), &sock->outStream());
58 peerEndpoint.buf = sock->getPeerEndpoint();
59 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
60
61 // Configure the socket
62 setSocketTimeouts();
63 lastEventTime = time(0);
64
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000065 server->clients.push_front(this);
66}
67
68
69VNCSConnectionST::~VNCSConnectionST()
70{
71 // If we reach here then VNCServerST is deleting us!
72 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
73 peerEndpoint.buf,
74 (closeReason.buf) ? closeReason.buf : "");
75
76 // Release any keys the client still had pressed
Pierre Ossman16e1dcb2017-05-16 14:33:43 +020077 while (!pressedKeys.empty()) {
78 rdr::U32 keysym, keycode;
79
80 keysym = pressedKeys.begin()->second;
81 keycode = pressedKeys.begin()->first;
82 pressedKeys.erase(pressedKeys.begin());
83
84 vlog.debug("Releasing key 0x%x / 0x%x on client disconnect",
85 keysym, keycode);
86 server->desktop->keyEvent(keysym, keycode, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +020087 }
Pierre Ossman16e1dcb2017-05-16 14:33:43 +020088
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000089 if (server->pointerClient == this)
90 server->pointerClient = 0;
91
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000092 // Remove this client from the server
93 server->clients.remove(this);
94
Pierre Ossman2c764942011-11-14 15:54:30 +000095 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000096}
97
98
99// Methods called from VNCServerST
100
101bool VNCSConnectionST::init()
102{
103 try {
104 initialiseProtocol();
105 } catch (rdr::Exception& e) {
106 close(e.str());
107 return false;
108 }
109 return true;
110}
111
112void VNCSConnectionST::close(const char* reason)
113{
114 // Log the reason for the close
115 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000116 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000117 else
118 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
119
120 if (authenticated()) {
121 server->lastDisconnectTime = time(0);
122 }
123
124 // Just shutdown the socket and mark our state as closing. Eventually the
125 // calling code will call VNCServerST's removeSocket() method causing us to
126 // be deleted.
127 sock->shutdown();
128 setState(RFBSTATE_CLOSING);
129}
130
131
132void VNCSConnectionST::processMessages()
133{
134 if (state() == RFBSTATE_CLOSING) return;
135 try {
136 // - Now set appropriate socket timeouts and process data
137 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000138
139 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000140
Pierre Ossmana830bec2011-11-08 12:12:02 +0000141 // Get the underlying TCP layer to build large packets if we send
142 // multiple small responses.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +0200143 sock->cork(true);
Pierre Ossmana830bec2011-11-08 12:12:02 +0000144
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000145 while (getInStream()->checkNoWait(1)) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000146 if (pendingSyncFence) {
147 syncFence = true;
148 pendingSyncFence = false;
149 }
150
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000151 processMsg();
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000152
Pierre Ossman2c764942011-11-14 15:54:30 +0000153 if (syncFence) {
154 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
155 syncFence = false;
156 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000157 }
158
Pierre Ossmana830bec2011-11-08 12:12:02 +0000159 // Flush out everything in case we go idle after this.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +0200160 sock->cork(false);
Pierre Ossmana830bec2011-11-08 12:12:02 +0000161
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000162 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000163
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000164 // If there were anything requiring an update, try to send it here.
165 // We wait until now with this to aggregate responses and to give
166 // higher priority to user actions such as keyboard and pointer events.
167 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000168 } catch (rdr::EndOfStream&) {
169 close("Clean disconnection");
170 } catch (rdr::Exception &e) {
171 close(e.str());
172 }
173}
174
Pierre Ossmand408ca52016-04-29 14:26:05 +0200175void VNCSConnectionST::flushSocket()
176{
177 if (state() == RFBSTATE_CLOSING) return;
178 try {
179 setSocketTimeouts();
180 sock->outStream().flush();
Pierre Ossmana40ab202016-04-29 15:35:56 +0200181 // Flushing the socket might release an update that was previously
182 // delayed because of congestion.
183 if (sock->outStream().bufferUsage() == 0)
184 writeFramebufferUpdate();
Pierre Ossmand408ca52016-04-29 14:26:05 +0200185 } catch (rdr::Exception &e) {
186 close(e.str());
187 }
188}
189
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000190void VNCSConnectionST::pixelBufferChange()
191{
192 try {
193 if (!authenticated()) return;
194 if (cp.width && cp.height && (server->pb->width() != cp.width ||
195 server->pb->height() != cp.height))
196 {
197 // We need to clip the next update to the new size, but also add any
198 // extra bits if it's bigger. If we wanted to do this exactly, something
199 // like the code below would do it, but at the moment we just update the
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200200 // entire new size. However, we do need to clip the damagedCursorRegion
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000201 // because that might be added to updates in writeFramebufferUpdate().
202
203 //updates.intersect(server->pb->getRect());
204 //
205 //if (server->pb->width() > cp.width)
206 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
207 // server->pb->height()));
208 //if (server->pb->height() > cp.height)
209 // updates.add_changed(Rect(0, cp.height, cp.width,
210 // server->pb->height()));
211
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200212 damagedCursorRegion.assign_intersect(server->pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000213
214 cp.width = server->pb->width();
215 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000216 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000217 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000218 // We should only send EDS to client asking for both
219 if (!writer()->writeExtendedDesktopSize()) {
220 if (!writer()->writeSetDesktopSize()) {
221 close("Client does not support desktop resize");
222 return;
223 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000224 }
225 }
226 }
227 // Just update the whole screen at the moment because we're too lazy to
228 // work out what's actually changed.
229 updates.clear();
230 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000231 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000232 } catch(rdr::Exception &e) {
233 close(e.str());
234 }
235}
236
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000237void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000238{
239 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000240 writeFramebufferUpdate();
241 } catch(rdr::Exception &e) {
242 close(e.str());
243 }
244}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000245
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000246void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
247{
248 try {
249 screenLayoutChange(reason);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100250 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000251 } catch(rdr::Exception &e) {
252 close(e.str());
253 }
254}
255
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000256void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000257{
258 try {
259 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
260 } catch(rdr::Exception& e) {
261 close(e.str());
262 }
263}
264
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000265void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000266{
267 try {
268 if (!(accessRights & AccessCutText)) return;
269 if (!rfb::Server::sendCutText) return;
270 if (state() == RFBSTATE_NORMAL)
271 writer()->writeServerCutText(str, len);
272 } catch(rdr::Exception& e) {
273 close(e.str());
274 }
275}
276
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000277
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000278void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000279{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000280 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000281 setDesktopName(name);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100282 writeFramebufferUpdate();
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000283 } catch(rdr::Exception& e) {
284 close(e.str());
285 }
286}
287
288
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000289void VNCSConnectionST::setCursorOrClose()
290{
291 try {
292 setCursor();
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100293 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000294 } catch(rdr::Exception& e) {
295 close(e.str());
296 }
297}
298
299
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100300void VNCSConnectionST::setLEDStateOrClose(unsigned int state)
301{
302 try {
303 setLEDState(state);
Pierre Ossmanb218ecd2017-11-16 16:43:13 +0100304 writeFramebufferUpdate();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100305 } catch(rdr::Exception& e) {
306 close(e.str());
307 }
308}
309
310
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000311int VNCSConnectionST::checkIdleTimeout()
312{
313 int idleTimeout = rfb::Server::idleTimeout;
314 if (idleTimeout == 0) return 0;
315 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
316 idleTimeout = 15; // minimum of 15 seconds while authenticating
317 time_t now = time(0);
318 if (now < lastEventTime) {
319 // Someone must have set the time backwards. Set lastEventTime so that the
320 // idleTimeout will count from now.
321 vlog.info("Time has gone backwards - resetting idle timeout");
322 lastEventTime = now;
323 }
324 int timeLeft = lastEventTime + idleTimeout - now;
325 if (timeLeft < -60) {
326 // Our callback is over a minute late - someone must have set the time
327 // forwards. Set lastEventTime so that the idleTimeout will count from
328 // now.
329 vlog.info("Time has gone forwards - resetting idle timeout");
330 lastEventTime = now;
331 return secsToMillis(idleTimeout);
332 }
333 if (timeLeft <= 0) {
334 close("Idle timeout");
335 return 0;
336 }
337 return secsToMillis(timeLeft);
338}
339
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000340
341bool VNCSConnectionST::getComparerState()
342{
343 // We interpret a low compression level as an indication that the client
344 // wants to prioritise CPU usage over bandwidth, and hence disable the
345 // comparing update tracker.
346 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
347}
348
349
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000350// renderedCursorChange() is called whenever the server-side rendered cursor
351// changes shape or position. It ensures that the next update will clean up
352// the old rendered cursor and if necessary draw the new rendered cursor.
353
354void VNCSConnectionST::renderedCursorChange()
355{
356 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200357 // Are we switching between client-side and server-side cursor?
Pierre Ossman25db44a2017-11-16 16:40:44 +0100358 if (clientHasCursor == needRenderedCursor())
Pierre Ossman71ca8d52017-09-15 11:03:12 +0200359 setCursorOrClose();
Pierre Ossman25db44a2017-11-16 16:40:44 +0100360 bool hasRenderedCursor = !damagedCursorRegion.is_empty();
Pierre Ossman330ca422017-11-06 13:15:55 +0100361 if (hasRenderedCursor)
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000362 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000363 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200364 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000365 writeFramebufferUpdateOrClose();
366 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000367}
368
369// needRenderedCursor() returns true if this client needs the server-side
370// rendered cursor. This may be because it does not support local cursor or
371// because the current cursor position has not been set by this client.
372// Unfortunately we can't know for sure when the current cursor position has
373// been set by this client. We guess that this is the case when the current
374// cursor position is the same as the last pointer event from this client, or
375// if it is a very short time since this client's last pointer event (up to a
376// second). [ Ideally we should do finer-grained timing here and make the time
377// configurable, but I don't think it's that important. ]
378
379bool VNCSConnectionST::needRenderedCursor()
380{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100381 if (state() != RFBSTATE_NORMAL)
382 return false;
383
Pierre Ossman324043e2017-08-16 16:26:11 +0200384 if (!cp.supportsLocalCursorWithAlpha &&
385 !cp.supportsLocalCursor && !cp.supportsLocalXCursor)
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100386 return true;
387 if (!server->cursorPos.equals(pointerEventPos) &&
388 (time(0) - pointerEventTime) > 0)
389 return true;
390
391 return false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000392}
393
394
395void VNCSConnectionST::approveConnectionOrClose(bool accept,
396 const char* reason)
397{
398 try {
399 approveConnection(accept, reason);
400 } catch (rdr::Exception& e) {
401 close(e.str());
402 }
403}
404
405
406
407// -=- Callbacks from SConnection
408
409void VNCSConnectionST::authSuccess()
410{
411 lastEventTime = time(0);
412
413 server->startDesktop();
414
415 // - Set the connection parameters appropriately
416 cp.width = server->pb->width();
417 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000418 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000419 cp.setName(server->getName());
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100420 cp.setLEDState(server->ledState);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000421
422 // - Set the default pixel format
423 cp.setPF(server->pb->getPF());
424 char buffer[256];
425 cp.pf().print(buffer, 256);
426 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)
572 if (!cp.supportsLEDState) {
573 // 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
677 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
678 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
679 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000680 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
681 } else {
682 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000683 }
684
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000685 // Just update the requested region.
686 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000687 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000688 if (!incremental || !continuousUpdates)
689 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000690
691 if (!incremental) {
692 // Non-incremental update - treat as if area requested has changed
693 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000694
695 // And send the screen layout to the client (which, unlike the
696 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000697 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000698
699 // We do not send a DesktopSize since it only contains the
700 // framebuffer size (which the client already should know) and
701 // because some clients don't handle extra DesktopSize events
702 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000703 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000704}
705
Pierre Ossman34bb0612009-03-21 21:16:14 +0000706void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
707 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000708{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000709 unsigned int result;
710
Michal Srbb318b8f2014-11-24 13:18:28 +0200711 if (!(accessRights & AccessSetDesktopSize)) return;
712 if (!rfb::Server::acceptSetDesktopSize) return;
713
Pierre Ossman04e62db2009-03-23 16:57:07 +0000714 // Don't bother the desktop with an invalid configuration
715 if (!layout.validate(fb_width, fb_height)) {
716 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
717 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000718 return;
719 }
720
721 // FIXME: the desktop will call back to VNCServerST and an extra set
722 // of ExtendedDesktopSize messages will be sent. This is okay
723 // protocol-wise, but unnecessary.
724 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
725
Pierre Ossman04e62db2009-03-23 16:57:07 +0000726 writer()->writeExtendedDesktopSize(reasonClient, result,
727 fb_width, fb_height, layout);
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
786 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
787 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
802// cp.supportsLocalCursor has changed. If the client does now support local
803// 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.
824 if (!cp.supportsFence)
825 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 {
Pierre Ossmana40ab202016-04-29 15:35:56 +0200839 if (t == &congestionTimer)
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100840 writeFramebufferUpdate();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000841 } catch (rdr::Exception& e) {
842 close(e.str());
843 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000844
845 return false;
846}
847
Pierre Ossman851e6802017-09-12 16:44:44 +0200848bool VNCSConnectionST::isShiftPressed()
849{
850 std::map<rdr::U32, rdr::U32>::const_iterator iter;
851
852 for (iter = pressedKeys.begin(); iter != pressedKeys.end(); ++iter) {
853 if (iter->second == XK_Shift_L)
854 return true;
855 if (iter->second == XK_Shift_R)
856 return true;
857 }
858
859 return false;
860}
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000861
Pierre Ossman1b478e52011-11-15 12:08:30 +0000862void VNCSConnectionST::writeRTTPing()
863{
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100864 char type;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000865
866 if (!cp.supportsFence)
867 return;
868
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100869 congestion.updatePosition(sock->outStream().length());
Pierre Ossman1b478e52011-11-15 12:08:30 +0000870
871 // We need to make sure any old update are already processed by the
872 // time we get the response back. This allows us to reliably throttle
873 // back on client overload, as well as network overload.
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100874 type = 1;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000875 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
Pierre Ossmanb2a417c2015-12-11 19:32:21 +0100876 sizeof(type), &type);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000877
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100878 congestion.sentPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000879}
880
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000881bool VNCSConnectionST::isCongested()
882{
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100883 unsigned eta;
884
885 congestionTimer.stop();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000886
887 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200888 sock->outStream().flush();
Pierre Ossman8cf71632016-03-11 09:38:08 +0100889 congestion.debugTrace("congestion-trace.csv", sock->getFd());
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000890 if (sock->outStream().bufferUsage() > 0)
891 return true;
892
Pierre Ossman1b478e52011-11-15 12:08:30 +0000893 if (!cp.supportsFence)
894 return false;
895
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100896 congestion.updatePosition(sock->outStream().length());
897 if (!congestion.isCongested())
Pierre Ossman1b478e52011-11-15 12:08:30 +0000898 return false;
899
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100900 eta = congestion.getUncongestedETA();
901 if (eta >= 0)
902 congestionTimer.start(eta);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000903
904 return true;
905}
906
907
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000908void VNCSConnectionST::writeFramebufferUpdate()
909{
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100910 congestion.updatePosition(sock->outStream().length());
911
Pierre Ossman2c764942011-11-14 15:54:30 +0000912 // We're in the middle of processing a command that's supposed to be
913 // synchronised. Allowing an update to slip out right now might violate
914 // that synchronisation.
915 if (syncFence)
916 return;
917
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000918 // We try to aggregate responses, so don't send out anything whilst we
919 // still have incoming messages. processMessages() will give us another
920 // chance to run once things are idle.
921 if (inProcessMessages)
922 return;
923
Pierre Ossman1b478e52011-11-15 12:08:30 +0000924 if (state() != RFBSTATE_NORMAL)
925 return;
926 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000927 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000928
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000929 // Check that we actually have some space on the link and retry in a
930 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +0200931 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000932 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000933
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100934 // Updates often consists of many small writes, and in continuous
935 // mode, we will also have small fence messages around the update. We
936 // need to aggregate these in order to not clog up TCP's congestion
937 // window.
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +0200938 sock->cork(true);
Pierre Ossman36dadf82011-11-15 12:11:32 +0000939
Pierre Ossmane9962f72009-04-23 12:31:42 +0000940 // First take care of any updates that cannot contain framebuffer data
941 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100942 writeNoDataUpdate();
943
944 // Then real data (if possible)
945 writeDataUpdate();
946
Peter Ã…strand (astrand)01dc1a62017-10-10 12:56:04 +0200947 sock->cork(false);
Pierre Ossmana99d14d2015-12-13 15:43:46 +0100948
949 congestion.updatePosition(sock->outStream().length());
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100950}
951
952void VNCSConnectionST::writeNoDataUpdate()
953{
954 if (!writer()->needNoDataUpdate())
955 return;
956
957 writer()->writeNoDataUpdate();
958
959 // Make sure no data update is sent until next request
960 requested.clear();
961}
962
963void VNCSConnectionST::writeDataUpdate()
964{
965 Region req;
966 UpdateInfo ui;
967 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +0100968 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000969
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000970 updates.enable_copyrect(cp.useCopyRect);
971
Pierre Ossman6e49e952016-10-07 15:59:38 +0200972 // See if we are allowed to send anything right now (the framebuffer
973 // might have changed in ways we haven't yet been informed of).
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000974 if (!server->checkUpdate())
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100975 return;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +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
986 // Get the lists of updates. Prior to exporting the data to the `ui' object,
987 // getUpdateInfo() will normalize the `updates' object such way that its
988 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +0000989 updates.getUpdateInfo(&ui, req);
990 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000991
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000992 // If the previous position of the rendered cursor overlaps the source of the
993 // copy, then when the copy happens the corresponding rectangle in the
994 // destination will be wrong, so add it to the changed region.
995
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200996 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
997 Region bogusCopiedCursor;
998
999 bogusCopiedCursor.copyFrom(damagedCursorRegion);
1000 bogusCopiedCursor.translate(ui.copy_delta);
1001 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001002 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001003 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001004 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001005 }
1006 }
1007
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001008 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001009 // the changed region.
1010
1011 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001012 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001013 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001014 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001015 removeRenderedCursor = false;
1016 }
1017
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001018 // If we need a full cursor update then make sure its entire region
1019 // is marked as changed.
1020
1021 if (updateRenderedCursor) {
1022 updates.add_changed(server->getRenderedCursor()->getEffectiveRect());
1023 needNewUpdateInfo = true;
1024 updateRenderedCursor = false;
1025 }
1026
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001027 // Return if there is nothing to send the client.
1028
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001029 if (updates.is_empty() && !writer()->needFakeUpdate())
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001030 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001031
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001032 // The `updates' object could change, make sure we have valid update info.
1033
1034 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001035 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001036
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001037 // Does the client need a server-side rendered cursor?
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001038
Pierre Ossman24684e52016-12-05 16:58:19 +01001039 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001040 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001041 Rect renderedCursorRect;
1042
Pierre Ossman24684e52016-12-05 16:58:19 +01001043 cursor = server->getRenderedCursor();
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001044 renderedCursorRect = cursor->getEffectiveRect();
Pierre Ossman24684e52016-12-05 16:58:19 +01001045
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001046 // Check that we don't try to copy over the cursor area, and
1047 // if that happens we need to treat it as changed so that we can
1048 // re-render it
1049 if (!ui.copied.intersect(renderedCursorRect).is_empty()) {
1050 ui.changed.assign_union(ui.copied.intersect(renderedCursorRect));
1051 ui.copied.assign_subtract(renderedCursorRect);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001052 }
1053
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001054 // Track where we've rendered the cursor
1055 damagedCursorRegion.assign_union(ui.changed.intersect(renderedCursorRect));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001056 }
1057
Pierre Ossman8c3bd692018-03-22 15:58:54 +01001058 if (ui.is_empty() && !writer()->needFakeUpdate())
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001059 return;
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001060
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001061 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001062
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001063 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001064
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001065 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001066
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001067 // The request might be for just part of the screen, so we cannot
1068 // just clear the entire update tracker.
1069 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001070
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001071 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001072}
1073
1074
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001075void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1076{
1077 if (!authenticated())
1078 return;
1079
1080 cp.screenLayout = server->screenLayout;
1081
1082 if (state() != RFBSTATE_NORMAL)
1083 return;
1084
1085 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1086 cp.screenLayout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001087}
1088
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001089
1090// setCursor() is called whenever the cursor has changed shape or pixel format.
1091// If the client supports local cursor then it will arrange for the cursor to
1092// be sent to the client.
1093
1094void VNCSConnectionST::setCursor()
1095{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001096 if (state() != RFBSTATE_NORMAL)
1097 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001098
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001099 // We need to blank out the client's cursor or there will be two
Pierre Ossman25db44a2017-11-16 16:40:44 +01001100 if (needRenderedCursor()) {
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001101 cp.setCursor(emptyCursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001102 clientHasCursor = false;
1103 } else {
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001104 cp.setCursor(*server->cursor);
Pierre Ossman25db44a2017-11-16 16:40:44 +01001105 clientHasCursor = true;
1106 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001107
Pierre Ossman8053c8e2017-02-21 12:59:04 +01001108 if (!writer()->writeSetCursorWithAlpha()) {
1109 if (!writer()->writeSetCursor()) {
1110 if (!writer()->writeSetXCursor()) {
1111 // No client support
1112 return;
1113 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001114 }
1115 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001116}
1117
1118void VNCSConnectionST::setDesktopName(const char *name)
1119{
1120 cp.setName(name);
1121
1122 if (state() != RFBSTATE_NORMAL)
1123 return;
1124
1125 if (!writer()->writeSetDesktopName()) {
1126 fprintf(stderr, "Client does not support desktop rename\n");
1127 return;
1128 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001129}
1130
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001131void VNCSConnectionST::setLEDState(unsigned int ledstate)
1132{
1133 if (state() != RFBSTATE_NORMAL)
1134 return;
1135
1136 cp.setLEDState(ledstate);
1137
Pierre Ossmanb218ecd2017-11-16 16:43:13 +01001138 writer()->writeLEDState();
Pierre Ossmanb45a84f2016-12-12 16:59:15 +01001139}
1140
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001141void VNCSConnectionST::setSocketTimeouts()
1142{
1143 int timeoutms = rfb::Server::clientWaitTimeMillis;
1144 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1145 if (timeoutms == 0)
1146 timeoutms = -1;
1147 sock->inStream().setTimeout(timeoutms);
1148 sock->outStream().setTimeout(timeoutms);
1149}
1150
1151char* VNCSConnectionST::getStartTime()
1152{
1153 char* result = ctime(&startTime);
1154 result[24] = '\0';
1155 return result;
1156}
1157
1158void VNCSConnectionST::setStatus(int status)
1159{
1160 switch (status) {
1161 case 0:
1162 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1163 break;
1164 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001165 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001166 break;
1167 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001168 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001169 break;
1170 }
1171 framebufferUpdateRequest(server->pb->getRect(), false);
1172}
1173int VNCSConnectionST::getStatus()
1174{
1175 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1176 return 0;
1177 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1178 return 1;
1179 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1180 return 2;
1181 return 4;
1182}
1183