blob: 53dd364a6ad89a307a631a6e0d273de294b8f882 [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
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000067VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
68 bool reverse)
Pierre Ossman7069bdd2015-02-06 14:41:58 +010069 : sock(s), reverseConnection(reverse),
Pierre Ossmanf8e3b342015-01-26 14:37:04 +010070 queryConnectTimer(this), inProcessMessages(false),
Pierre Ossmanb8b1e962012-07-20 10:47:00 +000071 pendingSyncFence(false), syncFence(false), fenceFlags(0),
72 fenceDataLen(0), fenceData(NULL),
Pierre Ossmanb1cd6ca2015-03-03 16:37:43 +010073 baseRTT(-1), congWindow(0), ackedOffset(0), sentOffset(0),
74 minRTT(-1), seenCongestion(false),
75 pingCounter(0), congestionTimer(this),
Pierre Ossman0c9bd4b2014-07-09 16:44:11 +020076 server(server_), updates(false),
Pierre Ossman671d2ef2015-06-09 16:09:06 +020077 updateRenderedCursor(false), removeRenderedCursor(false),
Pierre Ossmana40ab202016-04-29 15:35:56 +020078 continuousUpdates(false), encodeManager(this), pointerEventTime(0),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000079 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000080{
81 setStreams(&sock->inStream(), &sock->outStream());
82 peerEndpoint.buf = sock->getPeerEndpoint();
83 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
84
85 // Configure the socket
86 setSocketTimeouts();
87 lastEventTime = time(0);
88
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000089 server->clients.push_front(this);
90}
91
92
93VNCSConnectionST::~VNCSConnectionST()
94{
95 // If we reach here then VNCServerST is deleting us!
96 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
97 peerEndpoint.buf,
98 (closeReason.buf) ? closeReason.buf : "");
99
100 // Release any keys the client still had pressed
101 std::set<rdr::U32>::iterator i;
Pierre Ossman9a153b02015-08-31 10:01:14 +0200102 for (i=pressedKeys.begin(); i!=pressedKeys.end(); i++) {
103 vlog.debug("Releasing key 0x%x on client disconnect", *i);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000104 server->desktop->keyEvent(*i, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200105 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000106 if (server->pointerClient == this)
107 server->pointerClient = 0;
108
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000109 // Remove this client from the server
110 server->clients.remove(this);
111
Pierre Ossman2c764942011-11-14 15:54:30 +0000112 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000113}
114
115
116// Methods called from VNCServerST
117
118bool VNCSConnectionST::init()
119{
120 try {
121 initialiseProtocol();
122 } catch (rdr::Exception& e) {
123 close(e.str());
124 return false;
125 }
126 return true;
127}
128
129void VNCSConnectionST::close(const char* reason)
130{
131 // Log the reason for the close
132 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000133 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000134 else
135 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
136
137 if (authenticated()) {
138 server->lastDisconnectTime = time(0);
139 }
140
141 // Just shutdown the socket and mark our state as closing. Eventually the
142 // calling code will call VNCServerST's removeSocket() method causing us to
143 // be deleted.
144 sock->shutdown();
145 setState(RFBSTATE_CLOSING);
146}
147
148
149void VNCSConnectionST::processMessages()
150{
151 if (state() == RFBSTATE_CLOSING) return;
152 try {
153 // - Now set appropriate socket timeouts and process data
154 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000155
156 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000157
Pierre Ossmana830bec2011-11-08 12:12:02 +0000158 // Get the underlying TCP layer to build large packets if we send
159 // multiple small responses.
160 network::TcpSocket::cork(sock->getFd(), true);
161
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000162 while (getInStream()->checkNoWait(1)) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000163 if (pendingSyncFence) {
164 syncFence = true;
165 pendingSyncFence = false;
166 }
167
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000168 processMsg();
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000169
Pierre Ossman2c764942011-11-14 15:54:30 +0000170 if (syncFence) {
171 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
172 syncFence = false;
173 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000174 }
175
Pierre Ossmana830bec2011-11-08 12:12:02 +0000176 // Flush out everything in case we go idle after this.
177 network::TcpSocket::cork(sock->getFd(), false);
178
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000179 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000180
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000181 // If there were anything requiring an update, try to send it here.
182 // We wait until now with this to aggregate responses and to give
183 // higher priority to user actions such as keyboard and pointer events.
184 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000185 } catch (rdr::EndOfStream&) {
186 close("Clean disconnection");
187 } catch (rdr::Exception &e) {
188 close(e.str());
189 }
190}
191
Pierre Ossmand408ca52016-04-29 14:26:05 +0200192void VNCSConnectionST::flushSocket()
193{
194 if (state() == RFBSTATE_CLOSING) return;
195 try {
196 setSocketTimeouts();
197 sock->outStream().flush();
Pierre Ossmana40ab202016-04-29 15:35:56 +0200198 // Flushing the socket might release an update that was previously
199 // delayed because of congestion.
200 if (sock->outStream().bufferUsage() == 0)
201 writeFramebufferUpdate();
Pierre Ossmand408ca52016-04-29 14:26:05 +0200202 } catch (rdr::Exception &e) {
203 close(e.str());
204 }
205}
206
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000207void VNCSConnectionST::pixelBufferChange()
208{
209 try {
210 if (!authenticated()) return;
211 if (cp.width && cp.height && (server->pb->width() != cp.width ||
212 server->pb->height() != cp.height))
213 {
214 // We need to clip the next update to the new size, but also add any
215 // extra bits if it's bigger. If we wanted to do this exactly, something
216 // like the code below would do it, but at the moment we just update the
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200217 // entire new size. However, we do need to clip the damagedCursorRegion
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000218 // because that might be added to updates in writeFramebufferUpdate().
219
220 //updates.intersect(server->pb->getRect());
221 //
222 //if (server->pb->width() > cp.width)
223 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
224 // server->pb->height()));
225 //if (server->pb->height() > cp.height)
226 // updates.add_changed(Rect(0, cp.height, cp.width,
227 // server->pb->height()));
228
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200229 damagedCursorRegion.assign_intersect(server->pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000230
231 cp.width = server->pb->width();
232 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000233 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000234 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000235 // We should only send EDS to client asking for both
236 if (!writer()->writeExtendedDesktopSize()) {
237 if (!writer()->writeSetDesktopSize()) {
238 close("Client does not support desktop resize");
239 return;
240 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000241 }
242 }
243 }
244 // Just update the whole screen at the moment because we're too lazy to
245 // work out what's actually changed.
246 updates.clear();
247 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000248 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000249 } catch(rdr::Exception &e) {
250 close(e.str());
251 }
252}
253
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000254void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000255{
256 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000257 writeFramebufferUpdate();
258 } catch(rdr::Exception &e) {
259 close(e.str());
260 }
261}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000262
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000263void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
264{
265 try {
266 screenLayoutChange(reason);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000267 } catch(rdr::Exception &e) {
268 close(e.str());
269 }
270}
271
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000272void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000273{
274 try {
275 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
276 } catch(rdr::Exception& e) {
277 close(e.str());
278 }
279}
280
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000281void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000282{
283 try {
284 if (!(accessRights & AccessCutText)) return;
285 if (!rfb::Server::sendCutText) return;
286 if (state() == RFBSTATE_NORMAL)
287 writer()->writeServerCutText(str, len);
288 } catch(rdr::Exception& e) {
289 close(e.str());
290 }
291}
292
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000293
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000294void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000295{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000296 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000297 setDesktopName(name);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000298 } catch(rdr::Exception& e) {
299 close(e.str());
300 }
301}
302
303
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000304void VNCSConnectionST::setCursorOrClose()
305{
306 try {
307 setCursor();
308 } catch(rdr::Exception& e) {
309 close(e.str());
310 }
311}
312
313
314int VNCSConnectionST::checkIdleTimeout()
315{
316 int idleTimeout = rfb::Server::idleTimeout;
317 if (idleTimeout == 0) return 0;
318 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
319 idleTimeout = 15; // minimum of 15 seconds while authenticating
320 time_t now = time(0);
321 if (now < lastEventTime) {
322 // Someone must have set the time backwards. Set lastEventTime so that the
323 // idleTimeout will count from now.
324 vlog.info("Time has gone backwards - resetting idle timeout");
325 lastEventTime = now;
326 }
327 int timeLeft = lastEventTime + idleTimeout - now;
328 if (timeLeft < -60) {
329 // Our callback is over a minute late - someone must have set the time
330 // forwards. Set lastEventTime so that the idleTimeout will count from
331 // now.
332 vlog.info("Time has gone forwards - resetting idle timeout");
333 lastEventTime = now;
334 return secsToMillis(idleTimeout);
335 }
336 if (timeLeft <= 0) {
337 close("Idle timeout");
338 return 0;
339 }
340 return secsToMillis(timeLeft);
341}
342
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000343
344bool VNCSConnectionST::getComparerState()
345{
346 // We interpret a low compression level as an indication that the client
347 // wants to prioritise CPU usage over bandwidth, and hence disable the
348 // comparing update tracker.
349 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
350}
351
352
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000353// renderedCursorChange() is called whenever the server-side rendered cursor
354// changes shape or position. It ensures that the next update will clean up
355// the old rendered cursor and if necessary draw the new rendered cursor.
356
357void VNCSConnectionST::renderedCursorChange()
358{
359 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200360 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000361 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000362 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200363 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000364 writeFramebufferUpdateOrClose();
365 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000366}
367
368// needRenderedCursor() returns true if this client needs the server-side
369// rendered cursor. This may be because it does not support local cursor or
370// because the current cursor position has not been set by this client.
371// Unfortunately we can't know for sure when the current cursor position has
372// been set by this client. We guess that this is the case when the current
373// cursor position is the same as the last pointer event from this client, or
374// if it is a very short time since this client's last pointer event (up to a
375// second). [ Ideally we should do finer-grained timing here and make the time
376// configurable, but I don't think it's that important. ]
377
378bool VNCSConnectionST::needRenderedCursor()
379{
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100380 if (state() != RFBSTATE_NORMAL)
381 return false;
382
Pierre Ossman324043e2017-08-16 16:26:11 +0200383 if (!cp.supportsLocalCursorWithAlpha &&
384 !cp.supportsLocalCursor && !cp.supportsLocalXCursor)
Pierre Ossman77ede0a2016-12-05 16:57:30 +0100385 return true;
386 if (!server->cursorPos.equals(pointerEventPos) &&
387 (time(0) - pointerEventTime) > 0)
388 return true;
389
390 return false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000391}
392
393
394void VNCSConnectionST::approveConnectionOrClose(bool accept,
395 const char* reason)
396{
397 try {
398 approveConnection(accept, reason);
399 } catch (rdr::Exception& e) {
400 close(e.str());
401 }
402}
403
404
405
406// -=- Callbacks from SConnection
407
408void VNCSConnectionST::authSuccess()
409{
410 lastEventTime = time(0);
411
412 server->startDesktop();
413
414 // - Set the connection parameters appropriately
415 cp.width = server->pb->width();
416 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000417 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000418 cp.setName(server->getName());
419
420 // - Set the default pixel format
421 cp.setPF(server->pb->getPF());
422 char buffer[256];
423 cp.pf().print(buffer, 256);
424 vlog.info("Server default pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000425
426 // - Mark the entire display as "dirty"
427 updates.add_changed(server->pb->getRect());
428 startTime = time(0);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000429
430 // - Bootstrap the congestion control
431 ackedOffset = sock->outStream().length();
432 congWindow = INITIAL_WINDOW;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000433}
434
435void VNCSConnectionST::queryConnection(const char* userName)
436{
437 // - Authentication succeeded - clear from blacklist
438 CharArray name; name.buf = sock->getPeerAddress();
439 server->blHosts->clearBlackmark(name.buf);
440
441 // - Special case to provide a more useful error message
442 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
443 server->authClientCount() > 0) {
444 approveConnection(false, "The server is already in use");
445 return;
446 }
447
448 // - Does the client have the right to bypass the query?
449 if (reverseConnection ||
450 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
451 (accessRights & AccessNoQuery))
452 {
453 approveConnection(true);
454 return;
455 }
456
457 // - Get the server to display an Accept/Reject dialog, if required
458 // If a dialog is displayed, the result will be PENDING, and the
459 // server will call approveConnection at a later time
460 CharArray reason;
461 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
462 &reason.buf);
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100463 if (qr == VNCServerST::PENDING) {
464 queryConnectTimer.start(rfb::Server::queryConnectTimeout * 1000);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000465 return;
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100466 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000467
468 // - If server returns ACCEPT/REJECT then pass result to SConnection
469 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
470}
471
472void VNCSConnectionST::clientInit(bool shared)
473{
474 lastEventTime = time(0);
475 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100476 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000477 if (rfb::Server::neverShared) shared = false;
478 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100479 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000480 // - Close all the other connected clients
481 vlog.debug("non-shared connection - closing clients");
482 server->closeClients("Non-shared connection requested", getSock());
483 } else {
484 // - Refuse this connection if there are existing clients, in addition to
485 // this one
486 if (server->authClientCount() > 1) {
487 close("Server is already in use");
488 return;
489 }
490 }
491 }
492 SConnection::clientInit(shared);
493}
494
495void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
496{
497 SConnection::setPixelFormat(pf);
498 char buffer[256];
499 pf.print(buffer, 256);
500 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000501 setCursor();
502}
503
504void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
505{
506 pointerEventTime = lastEventTime = time(0);
507 server->lastUserInputTime = lastEventTime;
508 if (!(accessRights & AccessPtrEvents)) return;
509 if (!rfb::Server::acceptPointerEvents) return;
510 if (!server->pointerClient || server->pointerClient == this) {
511 pointerEventPos = pos;
512 if (buttonMask)
513 server->pointerClient = this;
514 else
515 server->pointerClient = 0;
516 server->desktop->pointerEvent(pointerEventPos, buttonMask);
517 }
518}
519
520
521class VNCSConnectionSTShiftPresser {
522public:
523 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
524 : desktop(desktop_), pressed(false) {}
525 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200526 if (pressed) {
527 vlog.debug("Releasing fake Shift_L");
528 desktop->keyEvent(XK_Shift_L, false);
529 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000530 }
531 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200532 vlog.debug("Pressing fake Shift_L");
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000533 desktop->keyEvent(XK_Shift_L, true);
534 pressed = true;
535 }
536 SDesktop* desktop;
537 bool pressed;
538};
539
540// keyEvent() - record in the pressedKeys which keys were pressed. Allow
541// multiple down events (for autorepeat), but only allow a single up event.
542void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
543 lastEventTime = time(0);
544 server->lastUserInputTime = lastEventTime;
545 if (!(accessRights & AccessKeyEvents)) return;
546 if (!rfb::Server::acceptKeyEvents) return;
547
Pierre Ossman9a153b02015-08-31 10:01:14 +0200548 if (down)
549 vlog.debug("Key pressed: 0x%x", key);
550 else
551 vlog.debug("Key released: 0x%x", key);
552
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000553 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200554 if (server->keyRemapper) {
555 rdr::U32 newkey;
556 newkey = server->keyRemapper->remapKey(key);
557 if (newkey != key) {
558 vlog.debug("Key remapped to 0x%x", newkey);
559 key = newkey;
560 }
561 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000562
563 // Turn ISO_Left_Tab into shifted Tab.
564 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
565 if (key == XK_ISO_Left_Tab) {
566 if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
567 pressedKeys.find(XK_Shift_R) == pressedKeys.end())
568 shiftPresser.press();
569 key = XK_Tab;
570 }
571
572 if (down) {
573 pressedKeys.insert(key);
574 } else {
575 if (!pressedKeys.erase(key)) return;
576 }
577 server->desktop->keyEvent(key, down);
578}
579
580void VNCSConnectionST::clientCutText(const char* str, int len)
581{
582 if (!(accessRights & AccessCutText)) return;
583 if (!rfb::Server::acceptCutText) return;
584 server->desktop->clientCutText(str, len);
585}
586
587void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
588{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000589 Rect safeRect;
590
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000591 if (!(accessRights & AccessView)) return;
592
593 SConnection::framebufferUpdateRequest(r, incremental);
594
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000595 // Check that the client isn't sending crappy requests
596 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
597 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
598 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000599 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
600 } else {
601 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000602 }
603
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000604 // Just update the requested region.
605 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000606 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000607 if (!incremental || !continuousUpdates)
608 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000609
610 if (!incremental) {
611 // Non-incremental update - treat as if area requested has changed
612 updates.add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000613
614 // And send the screen layout to the client (which, unlike the
615 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000616 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000617
618 // We do not send a DesktopSize since it only contains the
619 // framebuffer size (which the client already should know) and
620 // because some clients don't handle extra DesktopSize events
621 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000622 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000623}
624
Pierre Ossman34bb0612009-03-21 21:16:14 +0000625void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
626 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000627{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000628 unsigned int result;
629
Michal Srbb318b8f2014-11-24 13:18:28 +0200630 if (!(accessRights & AccessSetDesktopSize)) return;
631 if (!rfb::Server::acceptSetDesktopSize) return;
632
Pierre Ossman04e62db2009-03-23 16:57:07 +0000633 // Don't bother the desktop with an invalid configuration
634 if (!layout.validate(fb_width, fb_height)) {
635 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
636 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000637 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000638 return;
639 }
640
641 // FIXME: the desktop will call back to VNCServerST and an extra set
642 // of ExtendedDesktopSize messages will be sent. This is okay
643 // protocol-wise, but unnecessary.
644 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
645
Pierre Ossman04e62db2009-03-23 16:57:07 +0000646 writer()->writeExtendedDesktopSize(reasonClient, result,
647 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000648
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000649 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000650 if (result == resultSuccess) {
651 if (server->screenLayout != layout)
652 throw Exception("Desktop configured a different screen layout than requested");
653 server->notifyScreenLayoutChange(this);
654 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000655
656 // but always send back a reply to the requesting client
657 // (do this last as it might throw an exception on socket errors)
658 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000659}
660
Pierre Ossman2c764942011-11-14 15:54:30 +0000661void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
662{
663 if (flags & fenceFlagRequest) {
664 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000665 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000666
667 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
668 fenceDataLen = len;
669 delete [] fenceData;
Michal Srbf3afa242017-03-27 19:02:15 +0300670 fenceData = NULL;
Pierre Ossman2c764942011-11-14 15:54:30 +0000671 if (len > 0) {
672 fenceData = new char[len];
673 memcpy(fenceData, data, len);
674 }
675
676 return;
677 }
678
679 // We handle everything synchronously so we trivially honor these modes
680 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
681
682 writer()->writeFence(flags, len, data);
683 return;
684 }
685
Pierre Ossman1b478e52011-11-15 12:08:30 +0000686 struct RTTInfo rttInfo;
687
Pierre Ossman2c764942011-11-14 15:54:30 +0000688 switch (len) {
689 case 0:
690 // Initial dummy fence;
691 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000692 case sizeof(struct RTTInfo):
693 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
694 handleRTTPong(rttInfo);
695 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000696 default:
697 vlog.error("Fence response of unexpected size received");
698 }
699}
700
Pierre Ossman1b478e52011-11-15 12:08:30 +0000701void VNCSConnectionST::enableContinuousUpdates(bool enable,
702 int x, int y, int w, int h)
703{
704 Rect rect;
705
706 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
707 throw Exception("Client tried to enable continuous updates when not allowed");
708
709 continuousUpdates = enable;
710
711 rect.setXYWH(x, y, w, h);
712 cuRegion.reset(rect);
713
714 if (enable) {
715 requested.clear();
716 writeFramebufferUpdate();
717 } else {
718 writer()->writeEndOfContinuousUpdates();
719 }
720}
721
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000722// supportsLocalCursor() is called whenever the status of
723// cp.supportsLocalCursor has changed. If the client does now support local
724// cursor, we make sure that the old server-side rendered cursor is cleaned up
725// and the cursor is sent to the client.
726
727void VNCSConnectionST::supportsLocalCursor()
728{
Pierre Ossman324043e2017-08-16 16:26:11 +0200729 if (cp.supportsLocalCursorWithAlpha ||
730 cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200731 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000732 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000733 setCursor();
734 }
735}
736
Pierre Ossman2c764942011-11-14 15:54:30 +0000737void VNCSConnectionST::supportsFence()
738{
739 writer()->writeFence(fenceFlagRequest, 0, NULL);
740}
741
Pierre Ossman1b478e52011-11-15 12:08:30 +0000742void VNCSConnectionST::supportsContinuousUpdates()
743{
744 // We refuse to use continuous updates if we cannot monitor the buffer
745 // usage using fences.
746 if (!cp.supportsFence)
747 return;
748
749 writer()->writeEndOfContinuousUpdates();
750}
751
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000752
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000753bool VNCSConnectionST::handleTimeout(Timer* t)
754{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000755 try {
Pierre Ossmana40ab202016-04-29 15:35:56 +0200756 if (t == &congestionTimer)
Pierre Ossman1b478e52011-11-15 12:08:30 +0000757 updateCongestion();
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100758 else if (t == &queryConnectTimer) {
759 if (state() == RFBSTATE_QUERYING)
760 approveConnection(false, "The attempt to prompt the user to accept the connection failed");
761 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000762 } catch (rdr::Exception& e) {
763 close(e.str());
764 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000765
766 return false;
767}
768
769
Pierre Ossman1b478e52011-11-15 12:08:30 +0000770void VNCSConnectionST::writeRTTPing()
771{
772 struct RTTInfo rttInfo;
773
774 if (!cp.supportsFence)
775 return;
776
777 memset(&rttInfo, 0, sizeof(struct RTTInfo));
778
779 gettimeofday(&rttInfo.tv, NULL);
780 rttInfo.offset = sock->outStream().length();
781 rttInfo.inFlight = rttInfo.offset - ackedOffset;
782
783 // We need to make sure any old update are already processed by the
784 // time we get the response back. This allows us to reliably throttle
785 // back on client overload, as well as network overload.
786 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
787 sizeof(struct RTTInfo), (const char*)&rttInfo);
788
789 pingCounter++;
790
791 sentOffset = rttInfo.offset;
792
793 // Let some data flow before we adjust the settings
794 if (!congestionTimer.isStarted())
795 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
796}
797
798void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
799{
800 unsigned rtt, delay;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000801
802 pingCounter--;
803
804 rtt = msSince(&rttInfo.tv);
805 if (rtt < 1)
806 rtt = 1;
807
808 ackedOffset = rttInfo.offset;
809
810 // Try to estimate wire latency by tracking lowest seen latency
811 if (rtt < baseRTT)
812 baseRTT = rtt;
813
814 if (rttInfo.inFlight > congWindow) {
815 seenCongestion = true;
816
817 // Estimate added delay because of overtaxed buffers
818 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
819
820 if (delay < rtt)
821 rtt -= delay;
822 else
823 rtt = 1;
824
825 // If we underestimate the congestion window, then we'll get a latency
826 // that's less than the wire latency, which will confuse other portions
827 // of the code.
828 if (rtt < baseRTT)
829 rtt = baseRTT;
830 }
831
832 // We only keep track of the minimum latency seen (for a given interval)
klemens0536d092017-01-28 20:56:56 +0100833 // on the basis that we want to avoid continuous buffer issue, but don't
Pierre Ossman1b478e52011-11-15 12:08:30 +0000834 // mind (or even approve of) bursts.
835 if (rtt < minRTT)
836 minRTT = rtt;
837}
838
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000839bool VNCSConnectionST::isCongested()
840{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000841 int offset;
842
843 // Stuff still waiting in the send buffer?
Pierre Ossman352d0622016-04-29 15:50:54 +0200844 sock->outStream().flush();
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000845 if (sock->outStream().bufferUsage() > 0)
846 return true;
847
Pierre Ossman1b478e52011-11-15 12:08:30 +0000848 if (!cp.supportsFence)
849 return false;
850
851 // Idle for too long? (and no data on the wire)
852 //
853 // FIXME: This should really just be one baseRTT, but we're getting
854 // problems with triggering the idle timeout on each update.
855 // Maybe we need to use a moving average for the wire latency
856 // instead of baseRTT.
857 if ((sentOffset == ackedOffset) &&
858 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
859
860#ifdef CONGESTION_DEBUG
861 if (congWindow > INITIAL_WINDOW)
862 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
863 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
864#endif
865
866 // Close congestion window and allow a transfer
867 // FIXME: Reset baseRTT like Linux Vegas?
868 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
869
870 return false;
871 }
872
873 offset = sock->outStream().length();
874
875 // FIXME: Should we compensate for non-update data?
876 // (i.e. use sentOffset instead of offset)
877 if ((offset - ackedOffset) < congWindow)
878 return false;
879
880 // If we just have one outstanding "ping", that means the client has
881 // started receiving our update. In order to not regress compared to
882 // before we had congestion avoidance, we allow another update here.
883 // This could further clog up the tubes, but congestion control isn't
884 // really working properly right now anyway as the wire would otherwise
885 // be idle for at least RTT/2.
886 if (pingCounter == 1)
887 return false;
888
889 return true;
890}
891
892
893void VNCSConnectionST::updateCongestion()
894{
895 unsigned diff;
896
897 if (!seenCongestion)
898 return;
899
900 diff = minRTT - baseRTT;
901
902 if (diff > __rfbmin(100, baseRTT)) {
903 // Way too fast
904 congWindow = congWindow * baseRTT / minRTT;
905 } else if (diff > __rfbmin(50, baseRTT/2)) {
906 // Slightly too fast
907 congWindow -= 4096;
908 } else if (diff < 5) {
909 // Way too slow
910 congWindow += 8192;
911 } else if (diff < 25) {
912 // Too slow
913 congWindow += 4096;
914 }
915
916 if (congWindow < MINIMUM_WINDOW)
917 congWindow = MINIMUM_WINDOW;
918 if (congWindow > MAXIMUM_WINDOW)
919 congWindow = MAXIMUM_WINDOW;
920
921#ifdef CONGESTION_DEBUG
922 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
923 minRTT, baseRTT, congWindow / 1024,
924 congWindow * 8.0 / baseRTT / 1000.0);
925
926#ifdef TCP_INFO
927 struct tcp_info tcp_info;
928 socklen_t tcp_info_length;
929
930 tcp_info_length = sizeof(tcp_info);
931 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
932 (void *)&tcp_info, &tcp_info_length) == 0) {
933 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
934 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
935 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
936 }
937#endif
938
939#endif
940
941 minRTT = -1;
942 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000943}
944
945
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000946void VNCSConnectionST::writeFramebufferUpdate()
947{
Pierre Ossman2c764942011-11-14 15:54:30 +0000948 // We're in the middle of processing a command that's supposed to be
949 // synchronised. Allowing an update to slip out right now might violate
950 // that synchronisation.
951 if (syncFence)
952 return;
953
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000954 // We try to aggregate responses, so don't send out anything whilst we
955 // still have incoming messages. processMessages() will give us another
956 // chance to run once things are idle.
957 if (inProcessMessages)
958 return;
959
Pierre Ossman1b478e52011-11-15 12:08:30 +0000960 if (state() != RFBSTATE_NORMAL)
961 return;
962 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000963 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000964
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000965 // Check that we actually have some space on the link and retry in a
966 // bit if things are congested.
Pierre Ossmana40ab202016-04-29 15:35:56 +0200967 if (isCongested())
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000968 return;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000969
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100970 // Updates often consists of many small writes, and in continuous
971 // mode, we will also have small fence messages around the update. We
972 // need to aggregate these in order to not clog up TCP's congestion
973 // window.
Pierre Ossman36dadf82011-11-15 12:11:32 +0000974 network::TcpSocket::cork(sock->getFd(), true);
975
Pierre Ossmane9962f72009-04-23 12:31:42 +0000976 // First take care of any updates that cannot contain framebuffer data
977 // changes.
Pierre Ossmancef3cf72016-11-25 10:06:34 +0100978 writeNoDataUpdate();
979
980 // Then real data (if possible)
981 writeDataUpdate();
982
983 network::TcpSocket::cork(sock->getFd(), false);
984}
985
986void VNCSConnectionST::writeNoDataUpdate()
987{
988 if (!writer()->needNoDataUpdate())
989 return;
990
991 writer()->writeNoDataUpdate();
992
993 // Make sure no data update is sent until next request
994 requested.clear();
995}
996
997void VNCSConnectionST::writeDataUpdate()
998{
999 Region req;
1000 UpdateInfo ui;
1001 bool needNewUpdateInfo;
Pierre Ossman24684e52016-12-05 16:58:19 +01001002 const RenderedCursor *cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001003
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001004 updates.enable_copyrect(cp.useCopyRect);
1005
Pierre Ossman6e49e952016-10-07 15:59:38 +02001006 // See if we are allowed to send anything right now (the framebuffer
1007 // might have changed in ways we haven't yet been informed of).
Pierre Ossmanbbf955e2011-11-08 12:44:10 +00001008 if (!server->checkUpdate())
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001009 return;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +00001010
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001011 // See what the client has requested (if anything)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001012 if (continuousUpdates)
1013 req = cuRegion.union_(requested);
1014 else
1015 req = requested;
1016
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001017 if (req.is_empty())
1018 return;
1019
1020 // Get the lists of updates. Prior to exporting the data to the `ui' object,
1021 // getUpdateInfo() will normalize the `updates' object such way that its
1022 // `changed' and `copied' regions would not intersect.
Pierre Ossman1b478e52011-11-15 12:08:30 +00001023 updates.getUpdateInfo(&ui, req);
1024 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001025
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001026 // If the previous position of the rendered cursor overlaps the source of the
1027 // copy, then when the copy happens the corresponding rectangle in the
1028 // destination will be wrong, so add it to the changed region.
1029
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001030 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
1031 Region bogusCopiedCursor;
1032
1033 bogusCopiedCursor.copyFrom(damagedCursorRegion);
1034 bogusCopiedCursor.translate(ui.copy_delta);
1035 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001036 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001037 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001038 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001039 }
1040 }
1041
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001042 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001043 // the changed region.
1044
1045 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001046 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001047 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001048 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001049 removeRenderedCursor = false;
1050 }
1051
1052 // Return if there is nothing to send the client.
1053
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001054 if (updates.is_empty() && !writer()->needFakeUpdate() && !updateRenderedCursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001055 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001056
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001057 // The `updates' object could change, make sure we have valid update info.
1058
1059 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001060 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001061
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001062 // If the client needs a server-side rendered cursor, work out the cursor
1063 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1064 // with the update region, we need to draw the rendered cursor regardless of
1065 // whether it has changed.
1066
Pierre Ossman24684e52016-12-05 16:58:19 +01001067 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001068 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001069 Rect renderedCursorRect;
1070
Pierre Ossman24684e52016-12-05 16:58:19 +01001071 cursor = server->getRenderedCursor();
1072
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001073 renderedCursorRect
Pierre Ossman24684e52016-12-05 16:58:19 +01001074 = cursor->getEffectiveRect().intersect(req.get_bounding_rect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001075
1076 if (renderedCursorRect.is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001077 cursor = NULL;
1078 } else if (!updateRenderedCursor &&
1079 ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001080 .intersect(renderedCursorRect).is_empty()) {
Pierre Ossman24684e52016-12-05 16:58:19 +01001081 cursor = NULL;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001082 }
1083
Pierre Ossman5c037202016-12-05 17:00:35 +01001084 if (cursor) {
1085 updates.subtract(renderedCursorRect);
1086 updates.getUpdateInfo(&ui, req);
1087 }
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001088
1089 damagedCursorRegion.assign_union(renderedCursorRect);
1090 updateRenderedCursor = false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001091 }
1092
Pierre Ossman24684e52016-12-05 16:58:19 +01001093 if (ui.is_empty() && !writer()->needFakeUpdate() && !cursor)
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001094 return;
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001095
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001096 writeRTTPing();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001097
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001098 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001099
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001100 writeRTTPing();
Pierre Ossmanc0397262014-03-14 15:59:46 +01001101
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001102 // The request might be for just part of the screen, so we cannot
1103 // just clear the entire update tracker.
1104 updates.subtract(req);
Pierre Ossmanc0397262014-03-14 15:59:46 +01001105
Pierre Ossmancef3cf72016-11-25 10:06:34 +01001106 requested.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001107}
1108
1109
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001110void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1111{
1112 if (!authenticated())
1113 return;
1114
1115 cp.screenLayout = server->screenLayout;
1116
1117 if (state() != RFBSTATE_NORMAL)
1118 return;
1119
1120 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1121 cp.screenLayout);
1122 writeFramebufferUpdate();
1123}
1124
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001125
1126// setCursor() is called whenever the cursor has changed shape or pixel format.
1127// If the client supports local cursor then it will arrange for the cursor to
1128// be sent to the client.
1129
1130void VNCSConnectionST::setCursor()
1131{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001132 if (state() != RFBSTATE_NORMAL)
1133 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001134
Pierre Ossman6a1a0d02017-02-19 15:48:17 +01001135 cp.setCursor(*server->cursor);
Pierre Ossman126e5642014-02-13 14:40:25 +01001136
Pierre Ossman8053c8e2017-02-21 12:59:04 +01001137 if (!writer()->writeSetCursorWithAlpha()) {
1138 if (!writer()->writeSetCursor()) {
1139 if (!writer()->writeSetXCursor()) {
1140 // No client support
1141 return;
1142 }
Pierre Ossman126e5642014-02-13 14:40:25 +01001143 }
1144 }
1145
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001146 writeFramebufferUpdate();
1147}
1148
1149void VNCSConnectionST::setDesktopName(const char *name)
1150{
1151 cp.setName(name);
1152
1153 if (state() != RFBSTATE_NORMAL)
1154 return;
1155
1156 if (!writer()->writeSetDesktopName()) {
1157 fprintf(stderr, "Client does not support desktop rename\n");
1158 return;
1159 }
1160
1161 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001162}
1163
1164void VNCSConnectionST::setSocketTimeouts()
1165{
1166 int timeoutms = rfb::Server::clientWaitTimeMillis;
1167 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1168 if (timeoutms == 0)
1169 timeoutms = -1;
1170 sock->inStream().setTimeout(timeoutms);
1171 sock->outStream().setTimeout(timeoutms);
1172}
1173
1174char* VNCSConnectionST::getStartTime()
1175{
1176 char* result = ctime(&startTime);
1177 result[24] = '\0';
1178 return result;
1179}
1180
1181void VNCSConnectionST::setStatus(int status)
1182{
1183 switch (status) {
1184 case 0:
1185 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1186 break;
1187 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001188 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001189 break;
1190 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001191 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001192 break;
1193 }
1194 framebufferUpdateRequest(server->pb->getRect(), false);
1195}
1196int VNCSConnectionST::getStatus()
1197{
1198 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1199 return 0;
1200 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1201 return 1;
1202 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1203 return 2;
1204 return 4;
1205}
1206