blob: c92bdb4650e95bf98f66709ff56bcf46755d05a4 [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>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000037#include <rfb/ServerCore.h>
38#include <rfb/ComparingUpdateTracker.h>
39#include <rfb/KeyRemapper.h>
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +010040#include <rfb/Encoder.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000041#define XK_MISCELLANY
42#define XK_XKB_KEYS
43#include <rfb/keysymdef.h>
44
45using namespace rfb;
46
47static LogWriter vlog("VNCSConnST");
48
Pierre Ossman1b478e52011-11-15 12:08:30 +000049// This window should get us going fairly fast on a decent bandwidth network.
50// If it's too high, it will rapidly be reduced and stay low.
51static const unsigned INITIAL_WINDOW = 16384;
52
53// TCP's minimal window is 3*MSS. But since we don't know the MSS, we
klemens0536d092017-01-28 20:56:56 +010054// make a guess at 4 KiB (it's probably a bit higher).
Pierre Ossman1b478e52011-11-15 12:08:30 +000055static const unsigned MINIMUM_WINDOW = 4096;
56
57// The current default maximum window for Linux (4 MiB). Should be a good
58// limit for now...
59static const unsigned MAXIMUM_WINDOW = 4194304;
60
61struct RTTInfo {
62 struct timeval tv;
63 int offset;
64 unsigned inFlight;
65};
66
Pierre Ossman71ca8d52017-09-15 11:03:12 +020067static Cursor emptyCursor(0, 0, Point(0, 0), NULL);
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 Ossman71ca8d52017-09-15 11:03:12 +0200362 // Are we switching between client-side and server-side cursor?
363 if (damagedCursorRegion.is_empty() != needRenderedCursor())
364 setCursorOrClose();
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200365 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000366 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000367 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200368 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000369 writeFramebufferUpdateOrClose();
370 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000371}
372
373// needRenderedCursor() returns true if this client needs the server-side
374// rendered cursor. This may be because it does not support local cursor or
375// because the current cursor position has not been set by this client.
376// Unfortunately we can't know for sure when the current cursor position has
377// been set by this client. We guess that this is the case when the current
378// cursor position is the same as the last pointer event from this client, or
379// if it is a very short time since this client's last pointer event (up to a
380// second). [ Ideally we should do finer-grained timing here and make the time
381// configurable, but I don't think it's that important. ]
382
383bool VNCSConnectionST::needRenderedCursor()
384{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100385 if (state() != RFBSTATE_NORMAL)
386 return false;
387
Pierre Ossman324043e2017-08-16 16:26:11 +0200388 if (!cp.supportsLocalCursorWithAlpha &&
389 !cp.supportsLocalCursor && !cp.supportsLocalXCursor)
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100390 return true;
391 if (!server->cursorPos.equals(pointerEventPos) &&
392 (time(0) - pointerEventTime) > 0)
393 return true;
394
395 return false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000396}
397
398
399void VNCSConnectionST::approveConnectionOrClose(bool accept,
400 const char* reason)
401{
402 try {
403 approveConnection(accept, reason);
404 } catch (rdr::Exception& e) {
405 close(e.str());
406 }
407}
408
409
410
411// -=- Callbacks from SConnection
412
413void VNCSConnectionST::authSuccess()
414{
415 lastEventTime = time(0);
416
417 server->startDesktop();
418
419 // - Set the connection parameters appropriately
420 cp.width = server->pb->width();
421 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000422 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000423 cp.setName(server->getName());
424
425 // - Set the default pixel format
426 cp.setPF(server->pb->getPF());
427 char buffer[256];
428 cp.pf().print(buffer, 256);
429 vlog.info("Server default pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000430
431 // - Mark the entire display as "dirty"
432 updates.add_changed(server->pb->getRect());
433 startTime = time(0);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000434
435 // - Bootstrap the congestion control
436 ackedOffset = sock->outStream().length();
437 congWindow = INITIAL_WINDOW;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000438}
439
440void VNCSConnectionST::queryConnection(const char* userName)
441{
442 // - Authentication succeeded - clear from blacklist
443 CharArray name; name.buf = sock->getPeerAddress();
444 server->blHosts->clearBlackmark(name.buf);
445
446 // - Special case to provide a more useful error message
447 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
448 server->authClientCount() > 0) {
449 approveConnection(false, "The server is already in use");
450 return;
451 }
452
453 // - Does the client have the right to bypass the query?
454 if (reverseConnection ||
455 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
456 (accessRights & AccessNoQuery))
457 {
458 approveConnection(true);
459 return;
460 }
461
462 // - Get the server to display an Accept/Reject dialog, if required
463 // If a dialog is displayed, the result will be PENDING, and the
464 // server will call approveConnection at a later time
465 CharArray reason;
466 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
467 &reason.buf);
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100468 if (qr == VNCServerST::PENDING) {
469 queryConnectTimer.start(rfb::Server::queryConnectTimeout * 1000);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000470 return;
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100471 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000472
473 // - If server returns ACCEPT/REJECT then pass result to SConnection
474 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
475}
476
477void VNCSConnectionST::clientInit(bool shared)
478{
479 lastEventTime = time(0);
480 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100481 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000482 if (rfb::Server::neverShared) shared = false;
483 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100484 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000485 // - Close all the other connected clients
486 vlog.debug("non-shared connection - closing clients");
487 server->closeClients("Non-shared connection requested", getSock());
488 } else {
489 // - Refuse this connection if there are existing clients, in addition to
490 // this one
491 if (server->authClientCount() > 1) {
492 close("Server is already in use");
493 return;
494 }
495 }
496 }
497 SConnection::clientInit(shared);
498}
499
500void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
501{
502 SConnection::setPixelFormat(pf);
503 char buffer[256];
504 pf.print(buffer, 256);
505 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000506 setCursor();
507}
508
509void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
510{
511 pointerEventTime = lastEventTime = time(0);
512 server->lastUserInputTime = lastEventTime;
513 if (!(accessRights & AccessPtrEvents)) return;
514 if (!rfb::Server::acceptPointerEvents) return;
515 if (!server->pointerClient || server->pointerClient == this) {
516 pointerEventPos = pos;
517 if (buttonMask)
518 server->pointerClient = this;
519 else
520 server->pointerClient = 0;
521 server->desktop->pointerEvent(pointerEventPos, buttonMask);
522 }
523}
524
525
526class VNCSConnectionSTShiftPresser {
527public:
528 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
529 : desktop(desktop_), pressed(false) {}
530 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200531 if (pressed) {
532 vlog.debug("Releasing fake Shift_L");
533 desktop->keyEvent(XK_Shift_L, false);
534 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000535 }
536 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200537 vlog.debug("Pressing fake Shift_L");
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000538 desktop->keyEvent(XK_Shift_L, true);
539 pressed = true;
540 }
541 SDesktop* desktop;
542 bool pressed;
543};
544
545// keyEvent() - record in the pressedKeys which keys were pressed. Allow
546// multiple down events (for autorepeat), but only allow a single up event.
547void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
548 lastEventTime = time(0);
549 server->lastUserInputTime = lastEventTime;
550 if (!(accessRights & AccessKeyEvents)) return;
551 if (!rfb::Server::acceptKeyEvents) return;
552
Pierre Ossman9a153b02015-08-31 10:01:14 +0200553 if (down)
554 vlog.debug("Key pressed: 0x%x", key);
555 else
556 vlog.debug("Key released: 0x%x", key);
557
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000558 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200559 if (server->keyRemapper) {
560 rdr::U32 newkey;
561 newkey = server->keyRemapper->remapKey(key);
562 if (newkey != key) {
563 vlog.debug("Key remapped to 0x%x", newkey);
564 key = newkey;
565 }
566 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000567
568 // Turn ISO_Left_Tab into shifted Tab.
569 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
570 if (key == XK_ISO_Left_Tab) {
571 if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
572 pressedKeys.find(XK_Shift_R) == pressedKeys.end())
573 shiftPresser.press();
574 key = XK_Tab;
575 }
576
577 if (down) {
578 pressedKeys.insert(key);
579 } else {
580 if (!pressedKeys.erase(key)) return;
581 }
582 server->desktop->keyEvent(key, down);
583}
584
585void VNCSConnectionST::clientCutText(const char* str, int len)
586{
587 if (!(accessRights & AccessCutText)) return;
588 if (!rfb::Server::acceptCutText) return;
589 server->desktop->clientCutText(str, len);
590}
591
592void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
593{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000594 Rect safeRect;
595
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000596 if (!(accessRights & AccessView)) return;
597
598 SConnection::framebufferUpdateRequest(r, incremental);
599
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000600 // Check that the client isn't sending crappy requests
601 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
602 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
603 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000604 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
605 } else {
606 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000607 }
608
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000609 // Just update the requested region.
610 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000611 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000612 if (!incremental || !continuousUpdates)
613 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000614
615 if (!incremental) {
616 // Non-incremental update - treat as if area requested has changed
617 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000618
619 // And send the screen layout to the client (which, unlike the
620 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000621 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000622
623 // We do not send a DesktopSize since it only contains the
624 // framebuffer size (which the client already should know) and
625 // because some clients don't handle extra DesktopSize events
626 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000627 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000628}
629
Pierre Ossman34bb0612009-03-21 21:16:14 +0000630void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
631 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000632{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000633 unsigned int result;
634
Michal Srbb318b8f2014-11-24 13:18:28 +0200635 if (!(accessRights & AccessSetDesktopSize)) return;
636 if (!rfb::Server::acceptSetDesktopSize) return;
637
Pierre Ossman04e62db2009-03-23 16:57:07 +0000638 // Don't bother the desktop with an invalid configuration
639 if (!layout.validate(fb_width, fb_height)) {
640 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
641 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000642 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000643 return;
644 }
645
646 // FIXME: the desktop will call back to VNCServerST and an extra set
647 // of ExtendedDesktopSize messages will be sent. This is okay
648 // protocol-wise, but unnecessary.
649 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
650
Pierre Ossman04e62db2009-03-23 16:57:07 +0000651 writer()->writeExtendedDesktopSize(reasonClient, result,
652 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000653
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000654 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000655 if (result == resultSuccess) {
656 if (server->screenLayout != layout)
657 throw Exception("Desktop configured a different screen layout than requested");
658 server->notifyScreenLayoutChange(this);
659 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000660
661 // but always send back a reply to the requesting client
662 // (do this last as it might throw an exception on socket errors)
663 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000664}
665
Pierre Ossman2c764942011-11-14 15:54:30 +0000666void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
667{
668 if (flags & fenceFlagRequest) {
669 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000670 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000671
672 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
673 fenceDataLen = len;
674 delete [] fenceData;
Michal Srbf3afa242017-03-27 19:02:15 +0300675 fenceData = NULL;
Pierre Ossman2c764942011-11-14 15:54:30 +0000676 if (len > 0) {
677 fenceData = new char[len];
678 memcpy(fenceData, data, len);
679 }
680
681 return;
682 }
683
684 // We handle everything synchronously so we trivially honor these modes
685 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
686
687 writer()->writeFence(flags, len, data);
688 return;
689 }
690
Pierre Ossman1b478e52011-11-15 12:08:30 +0000691 struct RTTInfo rttInfo;
692
Pierre Ossman2c764942011-11-14 15:54:30 +0000693 switch (len) {
694 case 0:
695 // Initial dummy fence;
696 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000697 case sizeof(struct RTTInfo):
698 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
699 handleRTTPong(rttInfo);
700 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000701 default:
702 vlog.error("Fence response of unexpected size received");
703 }
704}
705
Pierre Ossman1b478e52011-11-15 12:08:30 +0000706void VNCSConnectionST::enableContinuousUpdates(bool enable,
707 int x, int y, int w, int h)
708{
709 Rect rect;
710
711 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
712 throw Exception("Client tried to enable continuous updates when not allowed");
713
714 continuousUpdates = enable;
715
716 rect.setXYWH(x, y, w, h);
717 cuRegion.reset(rect);
718
719 if (enable) {
720 requested.clear();
721 writeFramebufferUpdate();
722 } else {
723 writer()->writeEndOfContinuousUpdates();
724 }
725}
726
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000727// supportsLocalCursor() is called whenever the status of
728// cp.supportsLocalCursor has changed. If the client does now support local
729// cursor, we make sure that the old server-side rendered cursor is cleaned up
730// and the cursor is sent to the client.
731
732void VNCSConnectionST::supportsLocalCursor()
733{
Pierre Ossman324043e2017-08-16 16:26:11 +0200734 if (cp.supportsLocalCursorWithAlpha ||
735 cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200736 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000737 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000738 setCursor();
739 }
740}
741
Pierre Ossman2c764942011-11-14 15:54:30 +0000742void VNCSConnectionST::supportsFence()
743{
744 writer()->writeFence(fenceFlagRequest, 0, NULL);
745}
746
Pierre Ossman1b478e52011-11-15 12:08:30 +0000747void VNCSConnectionST::supportsContinuousUpdates()
748{
749 // We refuse to use continuous updates if we cannot monitor the buffer
750 // usage using fences.
751 if (!cp.supportsFence)
752 return;
753
754 writer()->writeEndOfContinuousUpdates();
755}
756
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000757
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000758bool VNCSConnectionST::handleTimeout(Timer* t)
759{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000760 try {
Pierre Ossmana40ab202016-04-29 15:35:56 +0200761 if (t == &congestionTimer)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000762 updateCongestion();
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100763 else if (t == &queryConnectTimer) {
764 if (state() == RFBSTATE_QUERYING)
765 approveConnection(false, "The attempt to prompt the user to accept the connection failed");
766 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000767 } catch (rdr::Exception& e) {
768 close(e.str());
769 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000770
771 return false;
772}
773
774
Pierre Ossman1b478e52011-11-15 12:08:30 +0000775void VNCSConnectionST::writeRTTPing()
776{
777 struct RTTInfo rttInfo;
778
779 if (!cp.supportsFence)
780 return;
781
782 memset(&rttInfo, 0, sizeof(struct RTTInfo));
783
784 gettimeofday(&rttInfo.tv, NULL);
785 rttInfo.offset = sock->outStream().length();
786 rttInfo.inFlight = rttInfo.offset - ackedOffset;
787
788 // We need to make sure any old update are already processed by the
789 // time we get the response back. This allows us to reliably throttle
790 // back on client overload, as well as network overload.
791 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
792 sizeof(struct RTTInfo), (const char*)&rttInfo);
793
794 pingCounter++;
795
796 sentOffset = rttInfo.offset;
797
798 // Let some data flow before we adjust the settings
799 if (!congestionTimer.isStarted())
800 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
801}
802
803void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
804{
805 unsigned rtt, delay;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000806
807 pingCounter--;
808
809 rtt = msSince(&rttInfo.tv);
810 if (rtt < 1)
811 rtt = 1;
812
813 ackedOffset = rttInfo.offset;
814
815 // Try to estimate wire latency by tracking lowest seen latency
816 if (rtt < baseRTT)
817 baseRTT = rtt;
818
819 if (rttInfo.inFlight > congWindow) {
820 seenCongestion = true;
821
822 // Estimate added delay because of overtaxed buffers
823 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
824
825 if (delay < rtt)
826 rtt -= delay;
827 else
828 rtt = 1;
829
830 // If we underestimate the congestion window, then we'll get a latency
831 // that's less than the wire latency, which will confuse other portions
832 // of the code.
833 if (rtt < baseRTT)
834 rtt = baseRTT;
835 }
836
837 // We only keep track of the minimum latency seen (for a given interval)
klemens0536d092017-01-28 20:56:56 +0100838 // on the basis that we want to avoid continuous buffer issue, but don't
Pierre Ossman1b478e52011-11-15 12:08:30 +0000839 // mind (or even approve of) bursts.
840 if (rtt < minRTT)
841 minRTT = rtt;
842}
843
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000844bool VNCSConnectionST::isCongested()
845{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000846 int offset;
847
848 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200849 sock->outStream().flush();
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000850 if (sock->outStream().bufferUsage() > 0)
851 return true;
852
Pierre Ossman1b478e52011-11-15 12:08:30 +0000853 if (!cp.supportsFence)
854 return false;
855
856 // Idle for too long? (and no data on the wire)
857 //
858 // FIXME: This should really just be one baseRTT, but we're getting
859 // problems with triggering the idle timeout on each update.
860 // Maybe we need to use a moving average for the wire latency
861 // instead of baseRTT.
862 if ((sentOffset == ackedOffset) &&
863 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
864
865#ifdef CONGESTION_DEBUG
866 if (congWindow > INITIAL_WINDOW)
867 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
868 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
869#endif
870
871 // Close congestion window and allow a transfer
872 // FIXME: Reset baseRTT like Linux Vegas?
873 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
874
875 return false;
876 }
877
878 offset = sock->outStream().length();
879
880 // FIXME: Should we compensate for non-update data?
881 // (i.e. use sentOffset instead of offset)
882 if ((offset - ackedOffset) < congWindow)
883 return false;
884
885 // If we just have one outstanding "ping", that means the client has
886 // started receiving our update. In order to not regress compared to
887 // before we had congestion avoidance, we allow another update here.
888 // This could further clog up the tubes, but congestion control isn't
889 // really working properly right now anyway as the wire would otherwise
890 // be idle for at least RTT/2.
891 if (pingCounter == 1)
892 return false;
893
894 return true;
895}
896
897
898void VNCSConnectionST::updateCongestion()
899{
900 unsigned diff;
901
902 if (!seenCongestion)
903 return;
904
905 diff = minRTT - baseRTT;
906
907 if (diff > __rfbmin(100, baseRTT)) {
908 // Way too fast
909 congWindow = congWindow * baseRTT / minRTT;
910 } else if (diff > __rfbmin(50, baseRTT/2)) {
911 // Slightly too fast
912 congWindow -= 4096;
913 } else if (diff < 5) {
914 // Way too slow
915 congWindow += 8192;
916 } else if (diff < 25) {
917 // Too slow
918 congWindow += 4096;
919 }
920
921 if (congWindow < MINIMUM_WINDOW)
922 congWindow = MINIMUM_WINDOW;
923 if (congWindow > MAXIMUM_WINDOW)
924 congWindow = MAXIMUM_WINDOW;
925
926#ifdef CONGESTION_DEBUG
927 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
928 minRTT, baseRTT, congWindow / 1024,
929 congWindow * 8.0 / baseRTT / 1000.0);
930
931#ifdef TCP_INFO
932 struct tcp_info tcp_info;
933 socklen_t tcp_info_length;
934
935 tcp_info_length = sizeof(tcp_info);
936 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
937 (void *)&tcp_info, &tcp_info_length) == 0) {
938 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
939 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
940 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
941 }
942#endif
943
944#endif
945
946 minRTT = -1;
947 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000948}
949
950
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000951void VNCSConnectionST::writeFramebufferUpdate()
952{
Pierre Ossman2c764942011-11-14 15:54:30 +0000953 // We're in the middle of processing a command that's supposed to be
954 // synchronised. Allowing an update to slip out right now might violate
955 // that synchronisation.
956 if (syncFence)
957 return;
958
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000959 // We try to aggregate responses, so don't send out anything whilst we
960 // still have incoming messages. processMessages() will give us another
961 // chance to run once things are idle.
962 if (inProcessMessages)
963 return;
964
Pierre Ossman1b478e52011-11-15 12:08:30 +0000965 if (state() != RFBSTATE_NORMAL)
966 return;
967 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000968 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000969
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000970 // Check that we actually have some space on the link and retry in a
971 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +0200972 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000973 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000974
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100975 // Updates often consists of many small writes, and in continuous
976 // mode, we will also have small fence messages around the update. We
977 // need to aggregate these in order to not clog up TCP's congestion
978 // window.
Pierre Ossman36dadf82011-11-15 12:11:32 +0000979 network::TcpSocket::cork(sock->getFd(), true);
980
Pierre Ossmane9962f72009-04-23 12:31:42 +0000981 // First take care of any updates that cannot contain framebuffer data
982 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100983 writeNoDataUpdate();
984
985 // Then real data (if possible)
986 writeDataUpdate();
987
988 network::TcpSocket::cork(sock->getFd(), false);
989}
990
991void VNCSConnectionST::writeNoDataUpdate()
992{
993 if (!writer()->needNoDataUpdate())
994 return;
995
996 writer()->writeNoDataUpdate();
997
998 // Make sure no data update is sent until next request
999 requested.clear();
1000}
1001
1002void VNCSConnectionST::writeDataUpdate()
1003{
1004 Region req;
1005 UpdateInfo ui;
1006 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +01001007 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001008
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001009 updates.enable_copyrect(cp.useCopyRect);
1010
Pierre Ossman6e49e952016-10-07 15:59:38 +02001011 // See if we are allowed to send anything right now (the framebuffer
1012 // might have changed in ways we haven't yet been informed of).
Pierre Ossmanbbf955e2011-11-08 12:44:10 +00001013 if (!server->checkUpdate())
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001014 return;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +00001015
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001016 // See what the client has requested (if anything)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001017 if (continuousUpdates)
1018 req = cuRegion.union_(requested);
1019 else
1020 req = requested;
1021
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001022 if (req.is_empty())
1023 return;
1024
1025 // Get the lists of updates. Prior to exporting the data to the `ui' object,
1026 // getUpdateInfo() will normalize the `updates' object such way that its
1027 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +00001028 updates.getUpdateInfo(&ui, req);
1029 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001030
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001031 // If the previous position of the rendered cursor overlaps the source of the
1032 // copy, then when the copy happens the corresponding rectangle in the
1033 // destination will be wrong, so add it to the changed region.
1034
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001035 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
1036 Region bogusCopiedCursor;
1037
1038 bogusCopiedCursor.copyFrom(damagedCursorRegion);
1039 bogusCopiedCursor.translate(ui.copy_delta);
1040 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001041 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001042 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001043 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001044 }
1045 }
1046
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001047 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001048 // the changed region.
1049
1050 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001051 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001052 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001053 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001054 removeRenderedCursor = false;
1055 }
1056
1057 // Return if there is nothing to send the client.
1058
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001059 if (updates.is_empty() && !writer()->needFakeUpdate() && !updateRenderedCursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001060 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001061
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001062 // The `updates' object could change, make sure we have valid update info.
1063
1064 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001065 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001066
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001067 // If the client needs a server-side rendered cursor, work out the cursor
1068 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1069 // with the update region, we need to draw the rendered cursor regardless of
1070 // whether it has changed.
1071
Pierre Ossman24684e52016-12-05 16:58:19 +01001072 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001073 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001074 Rect renderedCursorRect;
1075
Pierre Ossman24684e52016-12-05 16:58:19 +01001076 cursor = server->getRenderedCursor();
1077
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001078 renderedCursorRect
Pierre Ossman24684e52016-12-05 16:58:19 +01001079 = cursor->getEffectiveRect().intersect(req.get_bounding_rect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001080
1081 if (renderedCursorRect.is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001082 cursor = NULL;
1083 } else if (!updateRenderedCursor &&
1084 ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001085 .intersect(renderedCursorRect).is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001086 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001087 }
1088
Pierre Ossman5c037202016-12-05 17:00:35 +01001089 if (cursor) {
1090 updates.subtract(renderedCursorRect);
1091 updates.getUpdateInfo(&ui, req);
1092 }
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001093
1094 damagedCursorRegion.assign_union(renderedCursorRect);
1095 updateRenderedCursor = false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001096 }
1097
Pierre Ossman24684e52016-12-05 16:58:19 +01001098 if (ui.is_empty() && !writer()->needFakeUpdate() && !cursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001099 return;
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001100
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001101 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001102
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001103 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001104
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001105 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001106
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001107 // The request might be for just part of the screen, so we cannot
1108 // just clear the entire update tracker.
1109 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001110
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001111 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001112}
1113
1114
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001115void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1116{
1117 if (!authenticated())
1118 return;
1119
1120 cp.screenLayout = server->screenLayout;
1121
1122 if (state() != RFBSTATE_NORMAL)
1123 return;
1124
1125 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1126 cp.screenLayout);
1127 writeFramebufferUpdate();
1128}
1129
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001130
1131// setCursor() is called whenever the cursor has changed shape or pixel format.
1132// If the client supports local cursor then it will arrange for the cursor to
1133// be sent to the client.
1134
1135void VNCSConnectionST::setCursor()
1136{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001137 if (state() != RFBSTATE_NORMAL)
1138 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001139
Pierre Ossman71ca8d52017-09-15 11:03:12 +02001140 // We need to blank out the client's cursor or there will be two
1141 if (needRenderedCursor())
1142 cp.setCursor(emptyCursor);
1143 else
1144 cp.setCursor(*server->cursor);
Pierre Ossman126e5642014-02-13 14:40:25 +01001145
Pierre Ossman8053c8e2017-02-21 12:59:04 +01001146 if (!writer()->writeSetCursorWithAlpha()) {
1147 if (!writer()->writeSetCursor()) {
1148 if (!writer()->writeSetXCursor()) {
1149 // No client support
1150 return;
1151 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001152 }
1153 }
1154
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001155 writeFramebufferUpdate();
1156}
1157
1158void VNCSConnectionST::setDesktopName(const char *name)
1159{
1160 cp.setName(name);
1161
1162 if (state() != RFBSTATE_NORMAL)
1163 return;
1164
1165 if (!writer()->writeSetDesktopName()) {
1166 fprintf(stderr, "Client does not support desktop rename\n");
1167 return;
1168 }
1169
1170 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001171}
1172
1173void VNCSConnectionST::setSocketTimeouts()
1174{
1175 int timeoutms = rfb::Server::clientWaitTimeMillis;
1176 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1177 if (timeoutms == 0)
1178 timeoutms = -1;
1179 sock->inStream().setTimeout(timeoutms);
1180 sock->outStream().setTimeout(timeoutms);
1181}
1182
1183char* VNCSConnectionST::getStartTime()
1184{
1185 char* result = ctime(&startTime);
1186 result[24] = '\0';
1187 return result;
1188}
1189
1190void VNCSConnectionST::setStatus(int status)
1191{
1192 switch (status) {
1193 case 0:
1194 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1195 break;
1196 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001197 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001198 break;
1199 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001200 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001201 break;
1202 }
1203 framebufferUpdateRequest(server->pb->getRect(), false);
1204}
1205int VNCSConnectionST::getStatus()
1206{
1207 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1208 return 0;
1209 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1210 return 1;
1211 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1212 return 2;
1213 return 4;
1214}
1215