blob: de41e8fc8ccfe33f6cd47686a5d513329ab2ff10 [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossmancef3cf72016-11-25 10:06:34 +01002 * Copyright 2009-2016 Pierre Ossman for Cendio AB
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00003 *
4 * This is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This software is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this software; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17 * USA.
18 */
19
Pierre Ossman1b478e52011-11-15 12:08:30 +000020// Debug output on what the congestion control is up to
21#undef CONGESTION_DEBUG
22
23#include <sys/time.h>
24
25#ifdef CONGESTION_DEBUG
26#include <sys/socket.h>
27#include <netinet/in.h>
28#include <netinet/tcp.h>
29#endif
30
Pierre Ossmana830bec2011-11-08 12:12:02 +000031#include <network/TcpSocket.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000032#include <rfb/VNCSConnectionST.h>
33#include <rfb/LogWriter.h>
Adam Tkac5a0caed2010-04-23 13:58:10 +000034#include <rfb/Security.h>
Pierre Ossmanc5e25602009-03-20 12:59:05 +000035#include <rfb/screenTypes.h>
Pierre Ossman2c764942011-11-14 15:54:30 +000036#include <rfb/fenceTypes.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010037#include <rfb/ledStates.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000038#include <rfb/ServerCore.h>
39#include <rfb/ComparingUpdateTracker.h>
40#include <rfb/KeyRemapper.h>
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +010041#include <rfb/Encoder.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010042#define XK_LATIN1
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000043#define XK_MISCELLANY
44#define XK_XKB_KEYS
45#include <rfb/keysymdef.h>
46
47using namespace rfb;
48
49static LogWriter vlog("VNCSConnST");
50
Pierre Ossman1b478e52011-11-15 12:08:30 +000051// This window should get us going fairly fast on a decent bandwidth network.
52// If it's too high, it will rapidly be reduced and stay low.
53static const unsigned INITIAL_WINDOW = 16384;
54
55// TCP's minimal window is 3*MSS. But since we don't know the MSS, we
klemens0536d092017-01-28 20:56:56 +010056// make a guess at 4 KiB (it's probably a bit higher).
Pierre Ossman1b478e52011-11-15 12:08:30 +000057static const unsigned MINIMUM_WINDOW = 4096;
58
59// The current default maximum window for Linux (4 MiB). Should be a good
60// limit for now...
61static const unsigned MAXIMUM_WINDOW = 4194304;
62
63struct RTTInfo {
64 struct timeval tv;
65 int offset;
66 unsigned inFlight;
67};
68
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000069VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
70 bool reverse)
Pierre Ossman7069bdd2015-02-06 14:41:58 +010071 : sock(s), reverseConnection(reverse),
Pierre Ossmanf8e3b342015-01-26 14:37:04 +010072 queryConnectTimer(this), inProcessMessages(false),
Pierre Ossmanb8b1e962012-07-20 10:47:00 +000073 pendingSyncFence(false), syncFence(false), fenceFlags(0),
74 fenceDataLen(0), fenceData(NULL),
Pierre Ossmanb1cd6ca2015-03-03 16:37:43 +010075 baseRTT(-1), congWindow(0), ackedOffset(0), sentOffset(0),
76 minRTT(-1), seenCongestion(false),
77 pingCounter(0), congestionTimer(this),
Pierre Ossman0c9bd4b2014-07-09 16:44:11 +020078 server(server_), updates(false),
Pierre Ossman671d2ef2015-06-09 16:09:06 +020079 updateRenderedCursor(false), removeRenderedCursor(false),
Pierre Ossmana40ab202016-04-29 15:35:56 +020080 continuousUpdates(false), encodeManager(this), pointerEventTime(0),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000081 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000082{
83 setStreams(&sock->inStream(), &sock->outStream());
84 peerEndpoint.buf = sock->getPeerEndpoint();
85 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
86
87 // Configure the socket
88 setSocketTimeouts();
89 lastEventTime = time(0);
90
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000091 server->clients.push_front(this);
92}
93
94
95VNCSConnectionST::~VNCSConnectionST()
96{
97 // If we reach here then VNCServerST is deleting us!
98 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
99 peerEndpoint.buf,
100 (closeReason.buf) ? closeReason.buf : "");
101
102 // Release any keys the client still had pressed
103 std::set<rdr::U32>::iterator i;
Pierre Ossman9a153b02015-08-31 10:01:14 +0200104 for (i=pressedKeys.begin(); i!=pressedKeys.end(); i++) {
105 vlog.debug("Releasing key 0x%x on client disconnect", *i);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000106 server->desktop->keyEvent(*i, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200107 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000108 if (server->pointerClient == this)
109 server->pointerClient = 0;
110
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000111 // Remove this client from the server
112 server->clients.remove(this);
113
Pierre Ossman2c764942011-11-14 15:54:30 +0000114 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000115}
116
117
118// Methods called from VNCServerST
119
120bool VNCSConnectionST::init()
121{
122 try {
123 initialiseProtocol();
124 } catch (rdr::Exception& e) {
125 close(e.str());
126 return false;
127 }
128 return true;
129}
130
131void VNCSConnectionST::close(const char* reason)
132{
133 // Log the reason for the close
134 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000135 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000136 else
137 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
138
139 if (authenticated()) {
140 server->lastDisconnectTime = time(0);
141 }
142
143 // Just shutdown the socket and mark our state as closing. Eventually the
144 // calling code will call VNCServerST's removeSocket() method causing us to
145 // be deleted.
146 sock->shutdown();
147 setState(RFBSTATE_CLOSING);
148}
149
150
151void VNCSConnectionST::processMessages()
152{
153 if (state() == RFBSTATE_CLOSING) return;
154 try {
155 // - Now set appropriate socket timeouts and process data
156 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000157
158 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000159
Pierre Ossmana830bec2011-11-08 12:12:02 +0000160 // Get the underlying TCP layer to build large packets if we send
161 // multiple small responses.
162 network::TcpSocket::cork(sock->getFd(), true);
163
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000164 while (getInStream()->checkNoWait(1)) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000165 if (pendingSyncFence) {
166 syncFence = true;
167 pendingSyncFence = false;
168 }
169
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000170 processMsg();
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000171
Pierre Ossman2c764942011-11-14 15:54:30 +0000172 if (syncFence) {
173 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
174 syncFence = false;
175 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000176 }
177
Pierre Ossmana830bec2011-11-08 12:12:02 +0000178 // Flush out everything in case we go idle after this.
179 network::TcpSocket::cork(sock->getFd(), false);
180
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000181 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000182
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000183 // If there were anything requiring an update, try to send it here.
184 // We wait until now with this to aggregate responses and to give
185 // higher priority to user actions such as keyboard and pointer events.
186 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000187 } catch (rdr::EndOfStream&) {
188 close("Clean disconnection");
189 } catch (rdr::Exception &e) {
190 close(e.str());
191 }
192}
193
Pierre Ossmand408ca52016-04-29 14:26:05 +0200194void VNCSConnectionST::flushSocket()
195{
196 if (state() == RFBSTATE_CLOSING) return;
197 try {
198 setSocketTimeouts();
199 sock->outStream().flush();
Pierre Ossmana40ab202016-04-29 15:35:56 +0200200 // Flushing the socket might release an update that was previously
201 // delayed because of congestion.
202 if (sock->outStream().bufferUsage() == 0)
203 writeFramebufferUpdate();
Pierre Ossmand408ca52016-04-29 14:26:05 +0200204 } catch (rdr::Exception &e) {
205 close(e.str());
206 }
207}
208
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000209void VNCSConnectionST::pixelBufferChange()
210{
211 try {
212 if (!authenticated()) return;
213 if (cp.width && cp.height && (server->pb->width() != cp.width ||
214 server->pb->height() != cp.height))
215 {
216 // We need to clip the next update to the new size, but also add any
217 // extra bits if it's bigger. If we wanted to do this exactly, something
218 // like the code below would do it, but at the moment we just update the
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200219 // entire new size. However, we do need to clip the damagedCursorRegion
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000220 // because that might be added to updates in writeFramebufferUpdate().
221
222 //updates.intersect(server->pb->getRect());
223 //
224 //if (server->pb->width() > cp.width)
225 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
226 // server->pb->height()));
227 //if (server->pb->height() > cp.height)
228 // updates.add_changed(Rect(0, cp.height, cp.width,
229 // server->pb->height()));
230
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200231 damagedCursorRegion.assign_intersect(server->pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000232
233 cp.width = server->pb->width();
234 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000235 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000236 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000237 // We should only send EDS to client asking for both
238 if (!writer()->writeExtendedDesktopSize()) {
239 if (!writer()->writeSetDesktopSize()) {
240 close("Client does not support desktop resize");
241 return;
242 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000243 }
244 }
245 }
246 // Just update the whole screen at the moment because we're too lazy to
247 // work out what's actually changed.
248 updates.clear();
249 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000250 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000251 } catch(rdr::Exception &e) {
252 close(e.str());
253 }
254}
255
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000256void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000257{
258 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000259 writeFramebufferUpdate();
260 } catch(rdr::Exception &e) {
261 close(e.str());
262 }
263}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000264
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000265void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
266{
267 try {
268 screenLayoutChange(reason);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000269 } catch(rdr::Exception &e) {
270 close(e.str());
271 }
272}
273
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000274void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000275{
276 try {
277 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
278 } catch(rdr::Exception& e) {
279 close(e.str());
280 }
281}
282
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000283void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000284{
285 try {
286 if (!(accessRights & AccessCutText)) return;
287 if (!rfb::Server::sendCutText) return;
288 if (state() == RFBSTATE_NORMAL)
289 writer()->writeServerCutText(str, len);
290 } catch(rdr::Exception& e) {
291 close(e.str());
292 }
293}
294
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000295
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000296void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000297{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000298 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000299 setDesktopName(name);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000300 } catch(rdr::Exception& e) {
301 close(e.str());
302 }
303}
304
305
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000306void VNCSConnectionST::setCursorOrClose()
307{
308 try {
309 setCursor();
310 } catch(rdr::Exception& e) {
311 close(e.str());
312 }
313}
314
315
316int VNCSConnectionST::checkIdleTimeout()
317{
318 int idleTimeout = rfb::Server::idleTimeout;
319 if (idleTimeout == 0) return 0;
320 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
321 idleTimeout = 15; // minimum of 15 seconds while authenticating
322 time_t now = time(0);
323 if (now < lastEventTime) {
324 // Someone must have set the time backwards. Set lastEventTime so that the
325 // idleTimeout will count from now.
326 vlog.info("Time has gone backwards - resetting idle timeout");
327 lastEventTime = now;
328 }
329 int timeLeft = lastEventTime + idleTimeout - now;
330 if (timeLeft < -60) {
331 // Our callback is over a minute late - someone must have set the time
332 // forwards. Set lastEventTime so that the idleTimeout will count from
333 // now.
334 vlog.info("Time has gone forwards - resetting idle timeout");
335 lastEventTime = now;
336 return secsToMillis(idleTimeout);
337 }
338 if (timeLeft <= 0) {
339 close("Idle timeout");
340 return 0;
341 }
342 return secsToMillis(timeLeft);
343}
344
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000345
346bool VNCSConnectionST::getComparerState()
347{
348 // We interpret a low compression level as an indication that the client
349 // wants to prioritise CPU usage over bandwidth, and hence disable the
350 // comparing update tracker.
351 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
352}
353
354
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000355// renderedCursorChange() is called whenever the server-side rendered cursor
356// changes shape or position. It ensures that the next update will clean up
357// the old rendered cursor and if necessary draw the new rendered cursor.
358
359void VNCSConnectionST::renderedCursorChange()
360{
361 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200362 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000363 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000364 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200365 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000366 writeFramebufferUpdateOrClose();
367 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000368}
369
370// needRenderedCursor() returns true if this client needs the server-side
371// rendered cursor. This may be because it does not support local cursor or
372// because the current cursor position has not been set by this client.
373// Unfortunately we can't know for sure when the current cursor position has
374// been set by this client. We guess that this is the case when the current
375// cursor position is the same as the last pointer event from this client, or
376// if it is a very short time since this client's last pointer event (up to a
377// second). [ Ideally we should do finer-grained timing here and make the time
378// configurable, but I don't think it's that important. ]
379
380bool VNCSConnectionST::needRenderedCursor()
381{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100382 if (state() != RFBSTATE_NORMAL)
383 return false;
384
Pierre Ossman324043e2017-08-16 16:26:11 +0200385 if (!cp.supportsLocalCursorWithAlpha &&
386 !cp.supportsLocalCursor && !cp.supportsLocalXCursor)
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
417 cp.width = server->pb->width();
418 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000419 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000420 cp.setName(server->getName());
421
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);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000431
432 // - Bootstrap the congestion control
433 ackedOffset = sock->outStream().length();
434 congWindow = INITIAL_WINDOW;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000435}
436
437void VNCSConnectionST::queryConnection(const char* userName)
438{
439 // - Authentication succeeded - clear from blacklist
440 CharArray name; name.buf = sock->getPeerAddress();
441 server->blHosts->clearBlackmark(name.buf);
442
443 // - Special case to provide a more useful error message
444 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
445 server->authClientCount() > 0) {
446 approveConnection(false, "The server is already in use");
447 return;
448 }
449
450 // - Does the client have the right to bypass the query?
451 if (reverseConnection ||
452 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
453 (accessRights & AccessNoQuery))
454 {
455 approveConnection(true);
456 return;
457 }
458
459 // - Get the server to display an Accept/Reject dialog, if required
460 // If a dialog is displayed, the result will be PENDING, and the
461 // server will call approveConnection at a later time
462 CharArray reason;
463 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
464 &reason.buf);
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100465 if (qr == VNCServerST::PENDING) {
466 queryConnectTimer.start(rfb::Server::queryConnectTimeout * 1000);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000467 return;
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100468 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000469
470 // - If server returns ACCEPT/REJECT then pass result to SConnection
471 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
472}
473
474void VNCSConnectionST::clientInit(bool shared)
475{
476 lastEventTime = time(0);
477 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100478 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000479 if (rfb::Server::neverShared) shared = false;
480 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100481 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000482 // - Close all the other connected clients
483 vlog.debug("non-shared connection - closing clients");
484 server->closeClients("Non-shared connection requested", getSock());
485 } else {
486 // - Refuse this connection if there are existing clients, in addition to
487 // this one
488 if (server->authClientCount() > 1) {
489 close("Server is already in use");
490 return;
491 }
492 }
493 }
494 SConnection::clientInit(shared);
495}
496
497void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
498{
499 SConnection::setPixelFormat(pf);
500 char buffer[256];
501 pf.print(buffer, 256);
502 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000503 setCursor();
504}
505
506void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
507{
508 pointerEventTime = lastEventTime = time(0);
509 server->lastUserInputTime = lastEventTime;
510 if (!(accessRights & AccessPtrEvents)) return;
511 if (!rfb::Server::acceptPointerEvents) return;
512 if (!server->pointerClient || server->pointerClient == this) {
513 pointerEventPos = pos;
514 if (buttonMask)
515 server->pointerClient = this;
516 else
517 server->pointerClient = 0;
518 server->desktop->pointerEvent(pointerEventPos, buttonMask);
519 }
520}
521
522
523class VNCSConnectionSTShiftPresser {
524public:
525 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
526 : desktop(desktop_), pressed(false) {}
527 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200528 if (pressed) {
529 vlog.debug("Releasing fake Shift_L");
530 desktop->keyEvent(XK_Shift_L, false);
531 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000532 }
533 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200534 vlog.debug("Pressing fake Shift_L");
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000535 desktop->keyEvent(XK_Shift_L, true);
536 pressed = true;
537 }
538 SDesktop* desktop;
539 bool pressed;
540};
541
542// keyEvent() - record in the pressedKeys which keys were pressed. Allow
543// multiple down events (for autorepeat), but only allow a single up event.
544void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
545 lastEventTime = time(0);
546 server->lastUserInputTime = lastEventTime;
547 if (!(accessRights & AccessKeyEvents)) return;
548 if (!rfb::Server::acceptKeyEvents) return;
549
Pierre Ossman9a153b02015-08-31 10:01:14 +0200550 if (down)
551 vlog.debug("Key pressed: 0x%x", key);
552 else
553 vlog.debug("Key released: 0x%x", key);
554
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000555 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200556 if (server->keyRemapper) {
557 rdr::U32 newkey;
558 newkey = server->keyRemapper->remapKey(key);
559 if (newkey != key) {
560 vlog.debug("Key remapped to 0x%x", newkey);
561 key = newkey;
562 }
563 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000564
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100565 // Avoid lock keys if we don't know the server state
566 if ((server->ledState == ledUnknown) &&
567 ((key == XK_Caps_Lock) ||
568 (key == XK_Num_Lock) ||
569 (key == XK_Scroll_Lock))) {
570 vlog.debug("Ignoring lock key (e.g. caps lock)");
571 return;
572 }
573 // Always ignore ScrollLock though as we don't have a heuristic
574 // for that
575 if (key == XK_Scroll_Lock) {
576 vlog.debug("Ignoring lock key (e.g. caps lock)");
577 return;
578 }
579
580 if (down && (server->ledState != ledUnknown)) {
581 // CapsLock synchronisation heuristic
582 // (this assumes standard interaction between CapsLock the Shift
583 // keys and normal characters)
584 if (((key >= XK_A) && (key <= XK_Z)) ||
585 ((key >= XK_a) && (key <= XK_z))) {
586 bool uppercase, shift, lock;
587
588 uppercase = (key >= XK_A) && (key <= XK_Z);
589 shift = pressedKeys.find(XK_Shift_L) != pressedKeys.end() ||
590 pressedKeys.find(XK_Shift_R) != pressedKeys.end();
591 lock = server->ledState & ledCapsLock;
592
593 if (lock == (uppercase == shift)) {
594 vlog.debug("Inserting fake CapsLock to get in sync with client");
595 server->desktop->keyEvent(XK_Caps_Lock, true);
596 server->desktop->keyEvent(XK_Caps_Lock, false);
597 }
598 }
599
600 // NumLock synchronisation heuristic
601 // (this is more cautious because of the differences between Unix,
602 // Windows and macOS)
603 if (((key >= XK_KP_Home) && (key <= XK_KP_Delete)) ||
604 ((key >= XK_KP_0) && (key <= XK_KP_9)) ||
605 (key == XK_KP_Separator) || (key == XK_KP_Decimal)) {
606 bool number, shift, lock;
607
608 number = ((key >= XK_KP_0) && (key <= XK_KP_9)) ||
609 (key == XK_KP_Separator) || (key == XK_KP_Decimal);
610 shift = pressedKeys.find(XK_Shift_L) != pressedKeys.end() ||
611 pressedKeys.find(XK_Shift_R) != pressedKeys.end();
612 lock = server->ledState & ledNumLock;
613
614 if (shift) {
615 // We don't know the appropriate NumLock state for when Shift
616 // is pressed as it could be one of:
617 //
618 // a) A Unix client where Shift negates NumLock
619 //
620 // b) A Windows client where Shift only cancels NumLock
621 //
622 // c) A macOS client where Shift doesn't have any effect
623 //
624 } else if (lock == (number == shift)) {
625 vlog.debug("Inserting fake NumLock to get in sync with client");
626 server->desktop->keyEvent(XK_Num_Lock, true);
627 server->desktop->keyEvent(XK_Num_Lock, false);
628 }
629 }
630 }
631
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000632 // Turn ISO_Left_Tab into shifted Tab.
633 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
634 if (key == XK_ISO_Left_Tab) {
635 if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
636 pressedKeys.find(XK_Shift_R) == pressedKeys.end())
637 shiftPresser.press();
638 key = XK_Tab;
639 }
640
641 if (down) {
642 pressedKeys.insert(key);
643 } else {
644 if (!pressedKeys.erase(key)) return;
645 }
646 server->desktop->keyEvent(key, down);
647}
648
649void VNCSConnectionST::clientCutText(const char* str, int len)
650{
651 if (!(accessRights & AccessCutText)) return;
652 if (!rfb::Server::acceptCutText) return;
653 server->desktop->clientCutText(str, len);
654}
655
656void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
657{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000658 Rect safeRect;
659
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000660 if (!(accessRights & AccessView)) return;
661
662 SConnection::framebufferUpdateRequest(r, incremental);
663
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000664 // Check that the client isn't sending crappy requests
665 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
666 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
667 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000668 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
669 } else {
670 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000671 }
672
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000673 // Just update the requested region.
674 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000675 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000676 if (!incremental || !continuousUpdates)
677 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000678
679 if (!incremental) {
680 // Non-incremental update - treat as if area requested has changed
681 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000682
683 // And send the screen layout to the client (which, unlike the
684 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000685 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000686
687 // We do not send a DesktopSize since it only contains the
688 // framebuffer size (which the client already should know) and
689 // because some clients don't handle extra DesktopSize events
690 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000691 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000692}
693
Pierre Ossman34bb0612009-03-21 21:16:14 +0000694void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
695 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000696{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000697 unsigned int result;
698
Michal Srbb318b8f2014-11-24 13:18:28 +0200699 if (!(accessRights & AccessSetDesktopSize)) return;
700 if (!rfb::Server::acceptSetDesktopSize) return;
701
Pierre Ossman04e62db2009-03-23 16:57:07 +0000702 // Don't bother the desktop with an invalid configuration
703 if (!layout.validate(fb_width, fb_height)) {
704 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
705 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000706 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000707 return;
708 }
709
710 // FIXME: the desktop will call back to VNCServerST and an extra set
711 // of ExtendedDesktopSize messages will be sent. This is okay
712 // protocol-wise, but unnecessary.
713 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
714
Pierre Ossman04e62db2009-03-23 16:57:07 +0000715 writer()->writeExtendedDesktopSize(reasonClient, result,
716 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000717
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000718 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000719 if (result == resultSuccess) {
720 if (server->screenLayout != layout)
721 throw Exception("Desktop configured a different screen layout than requested");
722 server->notifyScreenLayoutChange(this);
723 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000724
725 // but always send back a reply to the requesting client
726 // (do this last as it might throw an exception on socket errors)
727 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000728}
729
Pierre Ossman2c764942011-11-14 15:54:30 +0000730void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
731{
732 if (flags & fenceFlagRequest) {
733 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000734 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000735
736 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
737 fenceDataLen = len;
738 delete [] fenceData;
Michal Srbf3afa242017-03-27 19:02:15 +0300739 fenceData = NULL;
Pierre Ossman2c764942011-11-14 15:54:30 +0000740 if (len > 0) {
741 fenceData = new char[len];
742 memcpy(fenceData, data, len);
743 }
744
745 return;
746 }
747
748 // We handle everything synchronously so we trivially honor these modes
749 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
750
751 writer()->writeFence(flags, len, data);
752 return;
753 }
754
Pierre Ossman1b478e52011-11-15 12:08:30 +0000755 struct RTTInfo rttInfo;
756
Pierre Ossman2c764942011-11-14 15:54:30 +0000757 switch (len) {
758 case 0:
759 // Initial dummy fence;
760 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000761 case sizeof(struct RTTInfo):
762 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
763 handleRTTPong(rttInfo);
764 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000765 default:
766 vlog.error("Fence response of unexpected size received");
767 }
768}
769
Pierre Ossman1b478e52011-11-15 12:08:30 +0000770void VNCSConnectionST::enableContinuousUpdates(bool enable,
771 int x, int y, int w, int h)
772{
773 Rect rect;
774
775 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
776 throw Exception("Client tried to enable continuous updates when not allowed");
777
778 continuousUpdates = enable;
779
780 rect.setXYWH(x, y, w, h);
781 cuRegion.reset(rect);
782
783 if (enable) {
784 requested.clear();
785 writeFramebufferUpdate();
786 } else {
787 writer()->writeEndOfContinuousUpdates();
788 }
789}
790
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000791// supportsLocalCursor() is called whenever the status of
792// cp.supportsLocalCursor has changed. If the client does now support local
793// cursor, we make sure that the old server-side rendered cursor is cleaned up
794// and the cursor is sent to the client.
795
796void VNCSConnectionST::supportsLocalCursor()
797{
Pierre Ossman324043e2017-08-16 16:26:11 +0200798 if (cp.supportsLocalCursorWithAlpha ||
799 cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200800 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000801 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000802 setCursor();
803 }
804}
805
Pierre Ossman2c764942011-11-14 15:54:30 +0000806void VNCSConnectionST::supportsFence()
807{
808 writer()->writeFence(fenceFlagRequest, 0, NULL);
809}
810
Pierre Ossman1b478e52011-11-15 12:08:30 +0000811void VNCSConnectionST::supportsContinuousUpdates()
812{
813 // We refuse to use continuous updates if we cannot monitor the buffer
814 // usage using fences.
815 if (!cp.supportsFence)
816 return;
817
818 writer()->writeEndOfContinuousUpdates();
819}
820
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000821
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000822bool VNCSConnectionST::handleTimeout(Timer* t)
823{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000824 try {
Pierre Ossmana40ab202016-04-29 15:35:56 +0200825 if (t == &congestionTimer)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000826 updateCongestion();
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100827 else if (t == &queryConnectTimer) {
828 if (state() == RFBSTATE_QUERYING)
829 approveConnection(false, "The attempt to prompt the user to accept the connection failed");
830 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000831 } catch (rdr::Exception& e) {
832 close(e.str());
833 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000834
835 return false;
836}
837
838
Pierre Ossman1b478e52011-11-15 12:08:30 +0000839void VNCSConnectionST::writeRTTPing()
840{
841 struct RTTInfo rttInfo;
842
843 if (!cp.supportsFence)
844 return;
845
846 memset(&rttInfo, 0, sizeof(struct RTTInfo));
847
848 gettimeofday(&rttInfo.tv, NULL);
849 rttInfo.offset = sock->outStream().length();
850 rttInfo.inFlight = rttInfo.offset - ackedOffset;
851
852 // We need to make sure any old update are already processed by the
853 // time we get the response back. This allows us to reliably throttle
854 // back on client overload, as well as network overload.
855 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
856 sizeof(struct RTTInfo), (const char*)&rttInfo);
857
858 pingCounter++;
859
860 sentOffset = rttInfo.offset;
861
862 // Let some data flow before we adjust the settings
863 if (!congestionTimer.isStarted())
864 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
865}
866
867void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
868{
869 unsigned rtt, delay;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000870
871 pingCounter--;
872
873 rtt = msSince(&rttInfo.tv);
874 if (rtt < 1)
875 rtt = 1;
876
877 ackedOffset = rttInfo.offset;
878
879 // Try to estimate wire latency by tracking lowest seen latency
880 if (rtt < baseRTT)
881 baseRTT = rtt;
882
883 if (rttInfo.inFlight > congWindow) {
884 seenCongestion = true;
885
886 // Estimate added delay because of overtaxed buffers
887 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
888
889 if (delay < rtt)
890 rtt -= delay;
891 else
892 rtt = 1;
893
894 // If we underestimate the congestion window, then we'll get a latency
895 // that's less than the wire latency, which will confuse other portions
896 // of the code.
897 if (rtt < baseRTT)
898 rtt = baseRTT;
899 }
900
901 // We only keep track of the minimum latency seen (for a given interval)
klemens0536d092017-01-28 20:56:56 +0100902 // on the basis that we want to avoid continuous buffer issue, but don't
Pierre Ossman1b478e52011-11-15 12:08:30 +0000903 // mind (or even approve of) bursts.
904 if (rtt < minRTT)
905 minRTT = rtt;
906}
907
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000908bool VNCSConnectionST::isCongested()
909{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000910 int offset;
911
912 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200913 sock->outStream().flush();
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000914 if (sock->outStream().bufferUsage() > 0)
915 return true;
916
Pierre Ossman1b478e52011-11-15 12:08:30 +0000917 if (!cp.supportsFence)
918 return false;
919
920 // Idle for too long? (and no data on the wire)
921 //
922 // FIXME: This should really just be one baseRTT, but we're getting
923 // problems with triggering the idle timeout on each update.
924 // Maybe we need to use a moving average for the wire latency
925 // instead of baseRTT.
926 if ((sentOffset == ackedOffset) &&
927 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
928
929#ifdef CONGESTION_DEBUG
930 if (congWindow > INITIAL_WINDOW)
931 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
932 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
933#endif
934
935 // Close congestion window and allow a transfer
936 // FIXME: Reset baseRTT like Linux Vegas?
937 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
938
939 return false;
940 }
941
942 offset = sock->outStream().length();
943
944 // FIXME: Should we compensate for non-update data?
945 // (i.e. use sentOffset instead of offset)
946 if ((offset - ackedOffset) < congWindow)
947 return false;
948
949 // If we just have one outstanding "ping", that means the client has
950 // started receiving our update. In order to not regress compared to
951 // before we had congestion avoidance, we allow another update here.
952 // This could further clog up the tubes, but congestion control isn't
953 // really working properly right now anyway as the wire would otherwise
954 // be idle for at least RTT/2.
955 if (pingCounter == 1)
956 return false;
957
958 return true;
959}
960
961
962void VNCSConnectionST::updateCongestion()
963{
964 unsigned diff;
965
966 if (!seenCongestion)
967 return;
968
969 diff = minRTT - baseRTT;
970
971 if (diff > __rfbmin(100, baseRTT)) {
972 // Way too fast
973 congWindow = congWindow * baseRTT / minRTT;
974 } else if (diff > __rfbmin(50, baseRTT/2)) {
975 // Slightly too fast
976 congWindow -= 4096;
977 } else if (diff < 5) {
978 // Way too slow
979 congWindow += 8192;
980 } else if (diff < 25) {
981 // Too slow
982 congWindow += 4096;
983 }
984
985 if (congWindow < MINIMUM_WINDOW)
986 congWindow = MINIMUM_WINDOW;
987 if (congWindow > MAXIMUM_WINDOW)
988 congWindow = MAXIMUM_WINDOW;
989
990#ifdef CONGESTION_DEBUG
991 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
992 minRTT, baseRTT, congWindow / 1024,
993 congWindow * 8.0 / baseRTT / 1000.0);
994
995#ifdef TCP_INFO
996 struct tcp_info tcp_info;
997 socklen_t tcp_info_length;
998
999 tcp_info_length = sizeof(tcp_info);
1000 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
1001 (void *)&tcp_info, &tcp_info_length) == 0) {
1002 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
1003 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
1004 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
1005 }
1006#endif
1007
1008#endif
1009
1010 minRTT = -1;
1011 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001012}
1013
1014
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001015void VNCSConnectionST::writeFramebufferUpdate()
1016{
Pierre Ossman2c764942011-11-14 15:54:30 +00001017 // We're in the middle of processing a command that's supposed to be
1018 // synchronised. Allowing an update to slip out right now might violate
1019 // that synchronisation.
1020 if (syncFence)
1021 return;
1022
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001023 // We try to aggregate responses, so don't send out anything whilst we
1024 // still have incoming messages. processMessages() will give us another
1025 // chance to run once things are idle.
1026 if (inProcessMessages)
1027 return;
1028
Pierre Ossman1b478e52011-11-15 12:08:30 +00001029 if (state() != RFBSTATE_NORMAL)
1030 return;
1031 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +00001032 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +00001033
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001034 // Check that we actually have some space on the link and retry in a
1035 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +02001036 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001037 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +00001038
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001039 // Updates often consists of many small writes, and in continuous
1040 // mode, we will also have small fence messages around the update. We
1041 // need to aggregate these in order to not clog up TCP's congestion
1042 // window.
Pierre Ossman36dadf82011-11-15 12:11:32 +00001043 network::TcpSocket::cork(sock->getFd(), true);
1044
Pierre Ossmane9962f72009-04-23 12:31:42 +00001045 // First take care of any updates that cannot contain framebuffer data
1046 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001047 writeNoDataUpdate();
1048
1049 // Then real data (if possible)
1050 writeDataUpdate();
1051
1052 network::TcpSocket::cork(sock->getFd(), false);
1053}
1054
1055void VNCSConnectionST::writeNoDataUpdate()
1056{
1057 if (!writer()->needNoDataUpdate())
1058 return;
1059
1060 writer()->writeNoDataUpdate();
1061
1062 // Make sure no data update is sent until next request
1063 requested.clear();
1064}
1065
1066void VNCSConnectionST::writeDataUpdate()
1067{
1068 Region req;
1069 UpdateInfo ui;
1070 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +01001071 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001072
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001073 updates.enable_copyrect(cp.useCopyRect);
1074
Pierre Ossman6e49e952016-10-07 15:59:38 +02001075 // See if we are allowed to send anything right now (the framebuffer
1076 // might have changed in ways we haven't yet been informed of).
Pierre Ossmanbbf955e2011-11-08 12:44:10 +00001077 if (!server->checkUpdate())
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001078 return;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +00001079
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001080 // See what the client has requested (if anything)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001081 if (continuousUpdates)
1082 req = cuRegion.union_(requested);
1083 else
1084 req = requested;
1085
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001086 if (req.is_empty())
1087 return;
1088
1089 // Get the lists of updates. Prior to exporting the data to the `ui' object,
1090 // getUpdateInfo() will normalize the `updates' object such way that its
1091 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +00001092 updates.getUpdateInfo(&ui, req);
1093 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001094
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001095 // If the previous position of the rendered cursor overlaps the source of the
1096 // copy, then when the copy happens the corresponding rectangle in the
1097 // destination will be wrong, so add it to the changed region.
1098
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001099 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
1100 Region bogusCopiedCursor;
1101
1102 bogusCopiedCursor.copyFrom(damagedCursorRegion);
1103 bogusCopiedCursor.translate(ui.copy_delta);
1104 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001105 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001106 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001107 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001108 }
1109 }
1110
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001111 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001112 // the changed region.
1113
1114 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001115 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001116 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001117 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001118 removeRenderedCursor = false;
1119 }
1120
1121 // Return if there is nothing to send the client.
1122
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001123 if (updates.is_empty() && !writer()->needFakeUpdate() && !updateRenderedCursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001124 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001125
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001126 // The `updates' object could change, make sure we have valid update info.
1127
1128 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001129 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001130
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001131 // If the client needs a server-side rendered cursor, work out the cursor
1132 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1133 // with the update region, we need to draw the rendered cursor regardless of
1134 // whether it has changed.
1135
Pierre Ossman24684e52016-12-05 16:58:19 +01001136 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001137 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001138 Rect renderedCursorRect;
1139
Pierre Ossman24684e52016-12-05 16:58:19 +01001140 cursor = server->getRenderedCursor();
1141
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001142 renderedCursorRect
Pierre Ossman24684e52016-12-05 16:58:19 +01001143 = cursor->getEffectiveRect().intersect(req.get_bounding_rect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001144
1145 if (renderedCursorRect.is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001146 cursor = NULL;
1147 } else if (!updateRenderedCursor &&
1148 ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001149 .intersect(renderedCursorRect).is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001150 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001151 }
1152
Pierre Ossman5c037202016-12-05 17:00:35 +01001153 if (cursor) {
1154 updates.subtract(renderedCursorRect);
1155 updates.getUpdateInfo(&ui, req);
1156 }
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001157
1158 damagedCursorRegion.assign_union(renderedCursorRect);
1159 updateRenderedCursor = false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001160 }
1161
Pierre Ossman24684e52016-12-05 16:58:19 +01001162 if (ui.is_empty() && !writer()->needFakeUpdate() && !cursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001163 return;
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001164
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001165 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001166
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001167 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001168
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001169 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001170
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001171 // The request might be for just part of the screen, so we cannot
1172 // just clear the entire update tracker.
1173 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001174
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001175 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001176}
1177
1178
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001179void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1180{
1181 if (!authenticated())
1182 return;
1183
1184 cp.screenLayout = server->screenLayout;
1185
1186 if (state() != RFBSTATE_NORMAL)
1187 return;
1188
1189 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1190 cp.screenLayout);
1191 writeFramebufferUpdate();
1192}
1193
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001194
1195// setCursor() is called whenever the cursor has changed shape or pixel format.
1196// If the client supports local cursor then it will arrange for the cursor to
1197// be sent to the client.
1198
1199void VNCSConnectionST::setCursor()
1200{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001201 if (state() != RFBSTATE_NORMAL)
1202 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001203
Pierre Ossman6a1a0d02017-02-19 15:48:17 +01001204 cp.setCursor(*server->cursor);
Pierre Ossman126e5642014-02-13 14:40:25 +01001205
Pierre Ossman8053c8e2017-02-21 12:59:04 +01001206 if (!writer()->writeSetCursorWithAlpha()) {
1207 if (!writer()->writeSetCursor()) {
1208 if (!writer()->writeSetXCursor()) {
1209 // No client support
1210 return;
1211 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001212 }
1213 }
1214
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001215 writeFramebufferUpdate();
1216}
1217
1218void VNCSConnectionST::setDesktopName(const char *name)
1219{
1220 cp.setName(name);
1221
1222 if (state() != RFBSTATE_NORMAL)
1223 return;
1224
1225 if (!writer()->writeSetDesktopName()) {
1226 fprintf(stderr, "Client does not support desktop rename\n");
1227 return;
1228 }
1229
1230 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001231}
1232
1233void VNCSConnectionST::setSocketTimeouts()
1234{
1235 int timeoutms = rfb::Server::clientWaitTimeMillis;
1236 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1237 if (timeoutms == 0)
1238 timeoutms = -1;
1239 sock->inStream().setTimeout(timeoutms);
1240 sock->outStream().setTimeout(timeoutms);
1241}
1242
1243char* VNCSConnectionST::getStartTime()
1244{
1245 char* result = ctime(&startTime);
1246 result[24] = '\0';
1247 return result;
1248}
1249
1250void VNCSConnectionST::setStatus(int status)
1251{
1252 switch (status) {
1253 case 0:
1254 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1255 break;
1256 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001257 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001258 break;
1259 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001260 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001261 break;
1262 }
1263 framebufferUpdateRequest(server->pb->getRect(), false);
1264}
1265int VNCSConnectionST::getStatus()
1266{
1267 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1268 return 0;
1269 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1270 return 1;
1271 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1272 return 2;
1273 return 4;
1274}
1275