blob: 932f579666cc2f1694c2fb5d81e34460d5f14d48 [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossmanf8e3b342015-01-26 14:37:04 +01002 * Copyright 2009-2015 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
54// make a guess at 4 KiB (it's probaly a bit higher).
55static 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 Ossmanc0397262014-03-14 15:59:46 +010078 continuousUpdates(false), encodeManager(this),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000079 updateTimer(this), pointerEventTime(0),
80 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000081{
82 setStreams(&sock->inStream(), &sock->outStream());
83 peerEndpoint.buf = sock->getPeerEndpoint();
84 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
85
86 // Configure the socket
87 setSocketTimeouts();
88 lastEventTime = time(0);
89
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000090 server->clients.push_front(this);
91}
92
93
94VNCSConnectionST::~VNCSConnectionST()
95{
96 // If we reach here then VNCServerST is deleting us!
97 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
98 peerEndpoint.buf,
99 (closeReason.buf) ? closeReason.buf : "");
100
101 // Release any keys the client still had pressed
102 std::set<rdr::U32>::iterator i;
Pierre Ossman9a153b02015-08-31 10:01:14 +0200103 for (i=pressedKeys.begin(); i!=pressedKeys.end(); i++) {
104 vlog.debug("Releasing key 0x%x on client disconnect", *i);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000105 server->desktop->keyEvent(*i, false);
Pierre Ossman9a153b02015-08-31 10:01:14 +0200106 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000107 if (server->pointerClient == this)
108 server->pointerClient = 0;
109
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000110 // Remove this client from the server
111 server->clients.remove(this);
112
Pierre Ossman2c764942011-11-14 15:54:30 +0000113 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000114}
115
116
117// Methods called from VNCServerST
118
119bool VNCSConnectionST::init()
120{
121 try {
122 initialiseProtocol();
123 } catch (rdr::Exception& e) {
124 close(e.str());
125 return false;
126 }
127 return true;
128}
129
130void VNCSConnectionST::close(const char* reason)
131{
132 // Log the reason for the close
133 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000134 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000135 else
136 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
137
138 if (authenticated()) {
139 server->lastDisconnectTime = time(0);
140 }
141
142 // Just shutdown the socket and mark our state as closing. Eventually the
143 // calling code will call VNCServerST's removeSocket() method causing us to
144 // be deleted.
145 sock->shutdown();
146 setState(RFBSTATE_CLOSING);
147}
148
149
150void VNCSConnectionST::processMessages()
151{
152 if (state() == RFBSTATE_CLOSING) return;
153 try {
154 // - Now set appropriate socket timeouts and process data
155 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000156
157 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000158
Pierre Ossmana830bec2011-11-08 12:12:02 +0000159 // Get the underlying TCP layer to build large packets if we send
160 // multiple small responses.
161 network::TcpSocket::cork(sock->getFd(), true);
162
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000163 while (getInStream()->checkNoWait(1)) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000164 if (pendingSyncFence) {
165 syncFence = true;
166 pendingSyncFence = false;
167 }
168
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000169 processMsg();
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000170
Pierre Ossman2c764942011-11-14 15:54:30 +0000171 if (syncFence) {
172 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
173 syncFence = false;
174 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000175 }
176
Pierre Ossmana830bec2011-11-08 12:12:02 +0000177 // Flush out everything in case we go idle after this.
178 network::TcpSocket::cork(sock->getFd(), false);
179
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000180 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000181
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000182 // If there were anything requiring an update, try to send it here.
183 // We wait until now with this to aggregate responses and to give
184 // higher priority to user actions such as keyboard and pointer events.
185 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000186 } catch (rdr::EndOfStream&) {
187 close("Clean disconnection");
188 } catch (rdr::Exception &e) {
189 close(e.str());
190 }
191}
192
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000193void VNCSConnectionST::pixelBufferChange()
194{
195 try {
196 if (!authenticated()) return;
197 if (cp.width && cp.height && (server->pb->width() != cp.width ||
198 server->pb->height() != cp.height))
199 {
200 // We need to clip the next update to the new size, but also add any
201 // extra bits if it's bigger. If we wanted to do this exactly, something
202 // like the code below would do it, but at the moment we just update the
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200203 // entire new size. However, we do need to clip the damagedCursorRegion
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000204 // because that might be added to updates in writeFramebufferUpdate().
205
206 //updates.intersect(server->pb->getRect());
207 //
208 //if (server->pb->width() > cp.width)
209 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
210 // server->pb->height()));
211 //if (server->pb->height() > cp.height)
212 // updates.add_changed(Rect(0, cp.height, cp.width,
213 // server->pb->height()));
214
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200215 damagedCursorRegion.assign_intersect(server->pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000216
217 cp.width = server->pb->width();
218 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000219 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000220 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000221 // We should only send EDS to client asking for both
222 if (!writer()->writeExtendedDesktopSize()) {
223 if (!writer()->writeSetDesktopSize()) {
224 close("Client does not support desktop resize");
225 return;
226 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000227 }
228 }
229 }
230 // Just update the whole screen at the moment because we're too lazy to
231 // work out what's actually changed.
232 updates.clear();
233 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000234 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000235 } catch(rdr::Exception &e) {
236 close(e.str());
237 }
238}
239
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000240void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000241{
242 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000243 writeFramebufferUpdate();
244 } catch(rdr::Exception &e) {
245 close(e.str());
246 }
247}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000248
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000249void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
250{
251 try {
252 screenLayoutChange(reason);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000253 } catch(rdr::Exception &e) {
254 close(e.str());
255 }
256}
257
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000258void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000259{
260 try {
261 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
262 } catch(rdr::Exception& e) {
263 close(e.str());
264 }
265}
266
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000267void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000268{
269 try {
270 if (!(accessRights & AccessCutText)) return;
271 if (!rfb::Server::sendCutText) return;
272 if (state() == RFBSTATE_NORMAL)
273 writer()->writeServerCutText(str, len);
274 } catch(rdr::Exception& e) {
275 close(e.str());
276 }
277}
278
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000279
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000280void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000281{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000282 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000283 setDesktopName(name);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000284 } catch(rdr::Exception& e) {
285 close(e.str());
286 }
287}
288
289
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000290void VNCSConnectionST::setCursorOrClose()
291{
292 try {
293 setCursor();
294 } catch(rdr::Exception& e) {
295 close(e.str());
296 }
297}
298
299
300int VNCSConnectionST::checkIdleTimeout()
301{
302 int idleTimeout = rfb::Server::idleTimeout;
303 if (idleTimeout == 0) return 0;
304 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
305 idleTimeout = 15; // minimum of 15 seconds while authenticating
306 time_t now = time(0);
307 if (now < lastEventTime) {
308 // Someone must have set the time backwards. Set lastEventTime so that the
309 // idleTimeout will count from now.
310 vlog.info("Time has gone backwards - resetting idle timeout");
311 lastEventTime = now;
312 }
313 int timeLeft = lastEventTime + idleTimeout - now;
314 if (timeLeft < -60) {
315 // Our callback is over a minute late - someone must have set the time
316 // forwards. Set lastEventTime so that the idleTimeout will count from
317 // now.
318 vlog.info("Time has gone forwards - resetting idle timeout");
319 lastEventTime = now;
320 return secsToMillis(idleTimeout);
321 }
322 if (timeLeft <= 0) {
323 close("Idle timeout");
324 return 0;
325 }
326 return secsToMillis(timeLeft);
327}
328
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000329
330bool VNCSConnectionST::getComparerState()
331{
332 // We interpret a low compression level as an indication that the client
333 // wants to prioritise CPU usage over bandwidth, and hence disable the
334 // comparing update tracker.
335 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
336}
337
338
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000339// renderedCursorChange() is called whenever the server-side rendered cursor
340// changes shape or position. It ensures that the next update will clean up
341// the old rendered cursor and if necessary draw the new rendered cursor.
342
343void VNCSConnectionST::renderedCursorChange()
344{
345 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200346 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000347 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000348 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200349 updateRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000350 writeFramebufferUpdateOrClose();
351 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000352}
353
354// needRenderedCursor() returns true if this client needs the server-side
355// rendered cursor. This may be because it does not support local cursor or
356// because the current cursor position has not been set by this client.
357// Unfortunately we can't know for sure when the current cursor position has
358// been set by this client. We guess that this is the case when the current
359// cursor position is the same as the last pointer event from this client, or
360// if it is a very short time since this client's last pointer event (up to a
361// second). [ Ideally we should do finer-grained timing here and make the time
362// configurable, but I don't think it's that important. ]
363
364bool VNCSConnectionST::needRenderedCursor()
365{
Peter Ã…strandffeeb262010-02-10 09:29:00 +0000366 bool pointerpos = (!server->cursorPos.equals(pointerEventPos) && (time(0) - pointerEventTime) > 0);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000367 return (state() == RFBSTATE_NORMAL
Peter Ã…strandffeeb262010-02-10 09:29:00 +0000368 && ((!cp.supportsLocalCursor && !cp.supportsLocalXCursor) || pointerpos));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000369}
370
371
372void VNCSConnectionST::approveConnectionOrClose(bool accept,
373 const char* reason)
374{
375 try {
376 approveConnection(accept, reason);
377 } catch (rdr::Exception& e) {
378 close(e.str());
379 }
380}
381
382
383
384// -=- Callbacks from SConnection
385
386void VNCSConnectionST::authSuccess()
387{
388 lastEventTime = time(0);
389
390 server->startDesktop();
391
392 // - Set the connection parameters appropriately
393 cp.width = server->pb->width();
394 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000395 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000396 cp.setName(server->getName());
397
398 // - Set the default pixel format
399 cp.setPF(server->pb->getPF());
400 char buffer[256];
401 cp.pf().print(buffer, 256);
402 vlog.info("Server default pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000403
404 // - Mark the entire display as "dirty"
405 updates.add_changed(server->pb->getRect());
406 startTime = time(0);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000407
408 // - Bootstrap the congestion control
409 ackedOffset = sock->outStream().length();
410 congWindow = INITIAL_WINDOW;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000411}
412
413void VNCSConnectionST::queryConnection(const char* userName)
414{
415 // - Authentication succeeded - clear from blacklist
416 CharArray name; name.buf = sock->getPeerAddress();
417 server->blHosts->clearBlackmark(name.buf);
418
419 // - Special case to provide a more useful error message
420 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
421 server->authClientCount() > 0) {
422 approveConnection(false, "The server is already in use");
423 return;
424 }
425
426 // - Does the client have the right to bypass the query?
427 if (reverseConnection ||
428 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
429 (accessRights & AccessNoQuery))
430 {
431 approveConnection(true);
432 return;
433 }
434
435 // - Get the server to display an Accept/Reject dialog, if required
436 // If a dialog is displayed, the result will be PENDING, and the
437 // server will call approveConnection at a later time
438 CharArray reason;
439 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
440 &reason.buf);
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100441 if (qr == VNCServerST::PENDING) {
442 queryConnectTimer.start(rfb::Server::queryConnectTimeout * 1000);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000443 return;
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100444 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000445
446 // - If server returns ACCEPT/REJECT then pass result to SConnection
447 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
448}
449
450void VNCSConnectionST::clientInit(bool shared)
451{
452 lastEventTime = time(0);
453 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100454 if (!(accessRights & AccessNonShared)) shared = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000455 if (rfb::Server::neverShared) shared = false;
456 if (!shared) {
Pierre Ossmane7be49b2014-12-02 14:33:17 +0100457 if (rfb::Server::disconnectClients && (accessRights & AccessNonShared)) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000458 // - Close all the other connected clients
459 vlog.debug("non-shared connection - closing clients");
460 server->closeClients("Non-shared connection requested", getSock());
461 } else {
462 // - Refuse this connection if there are existing clients, in addition to
463 // this one
464 if (server->authClientCount() > 1) {
465 close("Server is already in use");
466 return;
467 }
468 }
469 }
470 SConnection::clientInit(shared);
471}
472
473void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
474{
475 SConnection::setPixelFormat(pf);
476 char buffer[256];
477 pf.print(buffer, 256);
478 vlog.info("Client pixel format %s", buffer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000479 setCursor();
480}
481
482void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
483{
484 pointerEventTime = lastEventTime = time(0);
485 server->lastUserInputTime = lastEventTime;
486 if (!(accessRights & AccessPtrEvents)) return;
487 if (!rfb::Server::acceptPointerEvents) return;
488 if (!server->pointerClient || server->pointerClient == this) {
489 pointerEventPos = pos;
490 if (buttonMask)
491 server->pointerClient = this;
492 else
493 server->pointerClient = 0;
494 server->desktop->pointerEvent(pointerEventPos, buttonMask);
495 }
496}
497
498
499class VNCSConnectionSTShiftPresser {
500public:
501 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
502 : desktop(desktop_), pressed(false) {}
503 ~VNCSConnectionSTShiftPresser() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200504 if (pressed) {
505 vlog.debug("Releasing fake Shift_L");
506 desktop->keyEvent(XK_Shift_L, false);
507 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000508 }
509 void press() {
Pierre Ossman9a153b02015-08-31 10:01:14 +0200510 vlog.debug("Pressing fake Shift_L");
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000511 desktop->keyEvent(XK_Shift_L, true);
512 pressed = true;
513 }
514 SDesktop* desktop;
515 bool pressed;
516};
517
518// keyEvent() - record in the pressedKeys which keys were pressed. Allow
519// multiple down events (for autorepeat), but only allow a single up event.
520void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
521 lastEventTime = time(0);
522 server->lastUserInputTime = lastEventTime;
523 if (!(accessRights & AccessKeyEvents)) return;
524 if (!rfb::Server::acceptKeyEvents) return;
525
Pierre Ossman9a153b02015-08-31 10:01:14 +0200526 if (down)
527 vlog.debug("Key pressed: 0x%x", key);
528 else
529 vlog.debug("Key released: 0x%x", key);
530
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000531 // Remap the key if required
Pierre Ossman9a153b02015-08-31 10:01:14 +0200532 if (server->keyRemapper) {
533 rdr::U32 newkey;
534 newkey = server->keyRemapper->remapKey(key);
535 if (newkey != key) {
536 vlog.debug("Key remapped to 0x%x", newkey);
537 key = newkey;
538 }
539 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000540
541 // Turn ISO_Left_Tab into shifted Tab.
542 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
543 if (key == XK_ISO_Left_Tab) {
544 if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
545 pressedKeys.find(XK_Shift_R) == pressedKeys.end())
546 shiftPresser.press();
547 key = XK_Tab;
548 }
549
550 if (down) {
551 pressedKeys.insert(key);
552 } else {
553 if (!pressedKeys.erase(key)) return;
554 }
555 server->desktop->keyEvent(key, down);
556}
557
558void VNCSConnectionST::clientCutText(const char* str, int len)
559{
560 if (!(accessRights & AccessCutText)) return;
561 if (!rfb::Server::acceptCutText) return;
562 server->desktop->clientCutText(str, len);
563}
564
565void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
566{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000567 Rect safeRect;
568
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000569 if (!(accessRights & AccessView)) return;
570
571 SConnection::framebufferUpdateRequest(r, incremental);
572
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000573 // Check that the client isn't sending crappy requests
574 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
575 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
576 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000577 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
578 } else {
579 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000580 }
581
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000582 // Just update the requested region.
583 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000584 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000585 if (!incremental || !continuousUpdates)
586 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000587
588 if (!incremental) {
589 // Non-incremental update - treat as if area requested has changed
590 updates.add_changed(reqRgn);
591 server->comparer->add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000592
593 // And send the screen layout to the client (which, unlike the
594 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000595 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000596
597 // We do not send a DesktopSize since it only contains the
598 // framebuffer size (which the client already should know) and
599 // because some clients don't handle extra DesktopSize events
600 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000601 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000602}
603
Pierre Ossman34bb0612009-03-21 21:16:14 +0000604void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
605 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000606{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000607 unsigned int result;
608
Michal Srbb318b8f2014-11-24 13:18:28 +0200609 if (!(accessRights & AccessSetDesktopSize)) return;
610 if (!rfb::Server::acceptSetDesktopSize) return;
611
Pierre Ossman04e62db2009-03-23 16:57:07 +0000612 // Don't bother the desktop with an invalid configuration
613 if (!layout.validate(fb_width, fb_height)) {
614 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
615 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000616 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000617 return;
618 }
619
620 // FIXME: the desktop will call back to VNCServerST and an extra set
621 // of ExtendedDesktopSize messages will be sent. This is okay
622 // protocol-wise, but unnecessary.
623 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
624
Pierre Ossman04e62db2009-03-23 16:57:07 +0000625 writer()->writeExtendedDesktopSize(reasonClient, result,
626 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000627
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000628 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000629 if (result == resultSuccess) {
630 if (server->screenLayout != layout)
631 throw Exception("Desktop configured a different screen layout than requested");
632 server->notifyScreenLayoutChange(this);
633 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000634
635 // but always send back a reply to the requesting client
636 // (do this last as it might throw an exception on socket errors)
637 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000638}
639
Pierre Ossman2c764942011-11-14 15:54:30 +0000640void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
641{
642 if (flags & fenceFlagRequest) {
643 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000644 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000645
646 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
647 fenceDataLen = len;
648 delete [] fenceData;
649 if (len > 0) {
650 fenceData = new char[len];
651 memcpy(fenceData, data, len);
652 }
653
654 return;
655 }
656
657 // We handle everything synchronously so we trivially honor these modes
658 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
659
660 writer()->writeFence(flags, len, data);
661 return;
662 }
663
Pierre Ossman1b478e52011-11-15 12:08:30 +0000664 struct RTTInfo rttInfo;
665
Pierre Ossman2c764942011-11-14 15:54:30 +0000666 switch (len) {
667 case 0:
668 // Initial dummy fence;
669 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000670 case sizeof(struct RTTInfo):
671 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
672 handleRTTPong(rttInfo);
673 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000674 default:
675 vlog.error("Fence response of unexpected size received");
676 }
677}
678
Pierre Ossman1b478e52011-11-15 12:08:30 +0000679void VNCSConnectionST::enableContinuousUpdates(bool enable,
680 int x, int y, int w, int h)
681{
682 Rect rect;
683
684 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
685 throw Exception("Client tried to enable continuous updates when not allowed");
686
687 continuousUpdates = enable;
688
689 rect.setXYWH(x, y, w, h);
690 cuRegion.reset(rect);
691
692 if (enable) {
693 requested.clear();
694 writeFramebufferUpdate();
695 } else {
696 writer()->writeEndOfContinuousUpdates();
697 }
698}
699
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000700// supportsLocalCursor() is called whenever the status of
701// cp.supportsLocalCursor has changed. If the client does now support local
702// cursor, we make sure that the old server-side rendered cursor is cleaned up
703// and the cursor is sent to the client.
704
705void VNCSConnectionST::supportsLocalCursor()
706{
707 if (cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200708 if (!damagedCursorRegion.is_empty())
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000709 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000710 setCursor();
711 }
712}
713
Pierre Ossman2c764942011-11-14 15:54:30 +0000714void VNCSConnectionST::supportsFence()
715{
716 writer()->writeFence(fenceFlagRequest, 0, NULL);
717}
718
Pierre Ossman1b478e52011-11-15 12:08:30 +0000719void VNCSConnectionST::supportsContinuousUpdates()
720{
721 // We refuse to use continuous updates if we cannot monitor the buffer
722 // usage using fences.
723 if (!cp.supportsFence)
724 return;
725
726 writer()->writeEndOfContinuousUpdates();
727}
728
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000729
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000730bool VNCSConnectionST::handleTimeout(Timer* t)
731{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000732 try {
733 if (t == &updateTimer)
734 writeFramebufferUpdate();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000735 else if (t == &congestionTimer)
736 updateCongestion();
Pierre Ossmanf8e3b342015-01-26 14:37:04 +0100737 else if (t == &queryConnectTimer) {
738 if (state() == RFBSTATE_QUERYING)
739 approveConnection(false, "The attempt to prompt the user to accept the connection failed");
740 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000741 } catch (rdr::Exception& e) {
742 close(e.str());
743 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000744
745 return false;
746}
747
748
Pierre Ossman1b478e52011-11-15 12:08:30 +0000749void VNCSConnectionST::writeRTTPing()
750{
751 struct RTTInfo rttInfo;
752
753 if (!cp.supportsFence)
754 return;
755
756 memset(&rttInfo, 0, sizeof(struct RTTInfo));
757
758 gettimeofday(&rttInfo.tv, NULL);
759 rttInfo.offset = sock->outStream().length();
760 rttInfo.inFlight = rttInfo.offset - ackedOffset;
761
762 // We need to make sure any old update are already processed by the
763 // time we get the response back. This allows us to reliably throttle
764 // back on client overload, as well as network overload.
765 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
766 sizeof(struct RTTInfo), (const char*)&rttInfo);
767
768 pingCounter++;
769
770 sentOffset = rttInfo.offset;
771
772 // Let some data flow before we adjust the settings
773 if (!congestionTimer.isStarted())
774 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
775}
776
777void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
778{
779 unsigned rtt, delay;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000780
781 pingCounter--;
782
783 rtt = msSince(&rttInfo.tv);
784 if (rtt < 1)
785 rtt = 1;
786
787 ackedOffset = rttInfo.offset;
788
789 // Try to estimate wire latency by tracking lowest seen latency
790 if (rtt < baseRTT)
791 baseRTT = rtt;
792
793 if (rttInfo.inFlight > congWindow) {
794 seenCongestion = true;
795
796 // Estimate added delay because of overtaxed buffers
797 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
798
799 if (delay < rtt)
800 rtt -= delay;
801 else
802 rtt = 1;
803
804 // If we underestimate the congestion window, then we'll get a latency
805 // that's less than the wire latency, which will confuse other portions
806 // of the code.
807 if (rtt < baseRTT)
808 rtt = baseRTT;
809 }
810
811 // We only keep track of the minimum latency seen (for a given interval)
812 // on the basis that we want to avoid continous buffer issue, but don't
813 // mind (or even approve of) bursts.
814 if (rtt < minRTT)
815 minRTT = rtt;
816}
817
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000818bool VNCSConnectionST::isCongested()
819{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000820 int offset;
821
822 // Stuff still waiting in the send buffer?
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000823 if (sock->outStream().bufferUsage() > 0)
824 return true;
825
Pierre Ossman1b478e52011-11-15 12:08:30 +0000826 if (!cp.supportsFence)
827 return false;
828
829 // Idle for too long? (and no data on the wire)
830 //
831 // FIXME: This should really just be one baseRTT, but we're getting
832 // problems with triggering the idle timeout on each update.
833 // Maybe we need to use a moving average for the wire latency
834 // instead of baseRTT.
835 if ((sentOffset == ackedOffset) &&
836 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
837
838#ifdef CONGESTION_DEBUG
839 if (congWindow > INITIAL_WINDOW)
840 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
841 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
842#endif
843
844 // Close congestion window and allow a transfer
845 // FIXME: Reset baseRTT like Linux Vegas?
846 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
847
848 return false;
849 }
850
851 offset = sock->outStream().length();
852
853 // FIXME: Should we compensate for non-update data?
854 // (i.e. use sentOffset instead of offset)
855 if ((offset - ackedOffset) < congWindow)
856 return false;
857
858 // If we just have one outstanding "ping", that means the client has
859 // started receiving our update. In order to not regress compared to
860 // before we had congestion avoidance, we allow another update here.
861 // This could further clog up the tubes, but congestion control isn't
862 // really working properly right now anyway as the wire would otherwise
863 // be idle for at least RTT/2.
864 if (pingCounter == 1)
865 return false;
866
867 return true;
868}
869
870
871void VNCSConnectionST::updateCongestion()
872{
873 unsigned diff;
874
875 if (!seenCongestion)
876 return;
877
878 diff = minRTT - baseRTT;
879
880 if (diff > __rfbmin(100, baseRTT)) {
881 // Way too fast
882 congWindow = congWindow * baseRTT / minRTT;
883 } else if (diff > __rfbmin(50, baseRTT/2)) {
884 // Slightly too fast
885 congWindow -= 4096;
886 } else if (diff < 5) {
887 // Way too slow
888 congWindow += 8192;
889 } else if (diff < 25) {
890 // Too slow
891 congWindow += 4096;
892 }
893
894 if (congWindow < MINIMUM_WINDOW)
895 congWindow = MINIMUM_WINDOW;
896 if (congWindow > MAXIMUM_WINDOW)
897 congWindow = MAXIMUM_WINDOW;
898
899#ifdef CONGESTION_DEBUG
900 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
901 minRTT, baseRTT, congWindow / 1024,
902 congWindow * 8.0 / baseRTT / 1000.0);
903
904#ifdef TCP_INFO
905 struct tcp_info tcp_info;
906 socklen_t tcp_info_length;
907
908 tcp_info_length = sizeof(tcp_info);
909 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
910 (void *)&tcp_info, &tcp_info_length) == 0) {
911 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
912 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
913 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
914 }
915#endif
916
917#endif
918
919 minRTT = -1;
920 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000921}
922
923
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000924void VNCSConnectionST::writeFramebufferUpdate()
925{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000926 Region req;
927 UpdateInfo ui;
928 bool needNewUpdateInfo;
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200929 bool drawRenderedCursor;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000930
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000931 updateTimer.stop();
932
Pierre Ossman2c764942011-11-14 15:54:30 +0000933 // We're in the middle of processing a command that's supposed to be
934 // synchronised. Allowing an update to slip out right now might violate
935 // that synchronisation.
936 if (syncFence)
937 return;
938
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000939 // We try to aggregate responses, so don't send out anything whilst we
940 // still have incoming messages. processMessages() will give us another
941 // chance to run once things are idle.
942 if (inProcessMessages)
943 return;
944
Pierre Ossman1b478e52011-11-15 12:08:30 +0000945 if (state() != RFBSTATE_NORMAL)
946 return;
947 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000948 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000949
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000950 // Check that we actually have some space on the link and retry in a
951 // bit if things are congested.
952 if (isCongested()) {
953 updateTimer.start(50);
954 return;
955 }
956
Pierre Ossman36dadf82011-11-15 12:11:32 +0000957 // In continuous mode, we will be outputting at least three distinct
958 // messages. We need to aggregate these in order to not clog up TCP's
959 // congestion window.
960 network::TcpSocket::cork(sock->getFd(), true);
961
Pierre Ossmane9962f72009-04-23 12:31:42 +0000962 // First take care of any updates that cannot contain framebuffer data
963 // changes.
964 if (writer()->needNoDataUpdate()) {
965 writer()->writeNoDataUpdate();
966 requested.clear();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000967 if (!continuousUpdates)
Pierre Ossman36dadf82011-11-15 12:11:32 +0000968 goto out;
Pierre Ossmane9962f72009-04-23 12:31:42 +0000969 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000970
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000971 updates.enable_copyrect(cp.useCopyRect);
972
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000973 // Fetch updates from server object, and see if we are allowed to send
974 // anything right now (the framebuffer might have changed in ways we
975 // haven't yet been informed of).
976 if (!server->checkUpdate())
Pierre Ossman36dadf82011-11-15 12:11:32 +0000977 goto out;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +0000978
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000979 // Get the lists of updates. Prior to exporting the data to the `ui' object,
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000980 // getUpdateInfo() will normalize the `updates' object such way that its
Pierre Ossman02e43d72009-03-05 11:57:11 +0000981 // `changed' and `copied' regions would not intersect.
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000982
Pierre Ossman1b478e52011-11-15 12:08:30 +0000983 if (continuousUpdates)
984 req = cuRegion.union_(requested);
985 else
986 req = requested;
987
988 updates.getUpdateInfo(&ui, req);
989 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000990
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000991 // If the previous position of the rendered cursor overlaps the source of the
992 // copy, then when the copy happens the corresponding rectangle in the
993 // destination will be wrong, so add it to the changed region.
994
Pierre Ossman671d2ef2015-06-09 16:09:06 +0200995 if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
996 Region bogusCopiedCursor;
997
998 bogusCopiedCursor.copyFrom(damagedCursorRegion);
999 bogusCopiedCursor.translate(ui.copy_delta);
1000 bogusCopiedCursor.assign_intersect(server->pb->getRect());
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001001 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001002 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001003 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001004 }
1005 }
1006
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001007 // If we need to remove the old rendered cursor, just add the region to
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001008 // the changed region.
1009
1010 if (removeRenderedCursor) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001011 updates.add_changed(damagedCursorRegion);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001012 needNewUpdateInfo = true;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001013 damagedCursorRegion.clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001014 removeRenderedCursor = false;
1015 }
1016
1017 // Return if there is nothing to send the client.
1018
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001019 if (updates.is_empty() && !writer()->needFakeUpdate() && !updateRenderedCursor)
Pierre Ossman36dadf82011-11-15 12:11:32 +00001020 goto out;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001021
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001022 // The `updates' object could change, make sure we have valid update info.
1023
1024 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001025 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001026
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001027 // If the client needs a server-side rendered cursor, work out the cursor
1028 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1029 // with the update region, we need to draw the rendered cursor regardless of
1030 // whether it has changed.
1031
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001032 drawRenderedCursor = false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001033 if (needRenderedCursor()) {
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001034 Rect renderedCursorRect;
1035
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001036 renderedCursorRect
Pierre Ossman6ea6e1a2014-02-12 16:33:43 +01001037 = server->renderedCursor.getEffectiveRect()
1038 .intersect(req.get_bounding_rect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001039
1040 if (renderedCursorRect.is_empty()) {
1041 drawRenderedCursor = false;
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001042 } else if (updateRenderedCursor) {
1043 drawRenderedCursor = true;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001044 } else if (!ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001045 .intersect(renderedCursorRect).is_empty()) {
1046 drawRenderedCursor = true;
1047 }
1048
1049 // We could remove the new cursor rect from updates here. It's not clear
1050 // whether this is worth it. If we do remove it, then we won't draw over
1051 // the same bit of screen twice, but we have the overhead of a more complex
1052 // region.
1053
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001054 //if (drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001055 // updates.subtract(renderedCursorRect);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001056 // updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001057 //}
Pierre Ossman671d2ef2015-06-09 16:09:06 +02001058
1059 damagedCursorRegion.assign_union(renderedCursorRect);
1060 updateRenderedCursor = false;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001061 }
1062
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001063 if (!ui.is_empty() || writer()->needFakeUpdate() || drawRenderedCursor) {
Pierre Ossmanc0397262014-03-14 15:59:46 +01001064 RenderedCursor *cursor;
Pierre Ossmanfdba3fe2014-01-31 13:12:18 +01001065
Pierre Ossmanc0397262014-03-14 15:59:46 +01001066 cursor = NULL;
1067 if (drawRenderedCursor)
1068 cursor = &server->renderedCursor;
Pierre Ossman1b478e52011-11-15 12:08:30 +00001069
1070 writeRTTPing();
1071
Pierre Ossmanc0397262014-03-14 15:59:46 +01001072 encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
1073
1074 writeRTTPing();
1075
Pierre Ossmanb64dbf22015-06-09 16:10:39 +02001076 // The request might be for just part of the screen, so we cannot
1077 // just clear the entire update tracker.
Pierre Ossman3c56d4f2015-06-23 15:29:37 +02001078 updates.subtract(req);
Pierre Ossmanb64dbf22015-06-09 16:10:39 +02001079
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001080 requested.clear();
1081 }
Pierre Ossman36dadf82011-11-15 12:11:32 +00001082
1083out:
1084 network::TcpSocket::cork(sock->getFd(), false);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001085}
1086
1087
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001088void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1089{
1090 if (!authenticated())
1091 return;
1092
1093 cp.screenLayout = server->screenLayout;
1094
1095 if (state() != RFBSTATE_NORMAL)
1096 return;
1097
1098 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1099 cp.screenLayout);
1100 writeFramebufferUpdate();
1101}
1102
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001103
1104// setCursor() is called whenever the cursor has changed shape or pixel format.
1105// If the client supports local cursor then it will arrange for the cursor to
1106// be sent to the client.
1107
1108void VNCSConnectionST::setCursor()
1109{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001110 if (state() != RFBSTATE_NORMAL)
1111 return;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001112
Pierre Ossman126e5642014-02-13 14:40:25 +01001113 cp.setCursor(server->cursor);
1114
1115 if (!writer()->writeSetCursor()) {
1116 if (!writer()->writeSetXCursor()) {
1117 // No client support
1118 return;
1119 }
1120 }
1121
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001122 writeFramebufferUpdate();
1123}
1124
1125void VNCSConnectionST::setDesktopName(const char *name)
1126{
1127 cp.setName(name);
1128
1129 if (state() != RFBSTATE_NORMAL)
1130 return;
1131
1132 if (!writer()->writeSetDesktopName()) {
1133 fprintf(stderr, "Client does not support desktop rename\n");
1134 return;
1135 }
1136
1137 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001138}
1139
1140void VNCSConnectionST::setSocketTimeouts()
1141{
1142 int timeoutms = rfb::Server::clientWaitTimeMillis;
1143 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1144 if (timeoutms == 0)
1145 timeoutms = -1;
1146 sock->inStream().setTimeout(timeoutms);
1147 sock->outStream().setTimeout(timeoutms);
1148}
1149
1150char* VNCSConnectionST::getStartTime()
1151{
1152 char* result = ctime(&startTime);
1153 result[24] = '\0';
1154 return result;
1155}
1156
1157void VNCSConnectionST::setStatus(int status)
1158{
1159 switch (status) {
1160 case 0:
1161 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1162 break;
1163 case 1:
Pierre Ossman7728be22015-03-03 16:39:37 +01001164 accessRights = (accessRights & ~(AccessPtrEvents | AccessKeyEvents)) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001165 break;
1166 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001167 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001168 break;
1169 }
1170 framebufferUpdateRequest(server->pb->getRect(), false);
1171}
1172int VNCSConnectionST::getStatus()
1173{
1174 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1175 return 0;
1176 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1177 return 1;
1178 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1179 return 2;
1180 return 4;
1181}
1182