blob: 31ac5d1c2dba49abc9ab5234f3c1e652f00a24a2 [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +01002 * Copyright 2009-2018 Pierre Ossman for Cendio AB
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00003 *
4 * This is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * This software is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this software; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
17 * USA.
18 */
19
20// -=- Single-Threaded VNC Server implementation
21
22
23// Note about how sockets get closed:
24//
25// Closing sockets to clients is non-trivial because the code which calls
26// VNCServerST must explicitly know about all the sockets (so that it can block
27// on them appropriately). However, VNCServerST may want to close clients for
28// a number of reasons, and from a variety of entry points. The simplest is
29// when processSocketEvent() is called for a client, and the remote end has
30// closed its socket. A more complex reason is when processSocketEvent() is
31// called for a client which has just sent a ClientInit with the shared flag
32// set to false - in this case we want to close all other clients. Yet another
33// reason for disconnecting clients is when the desktop size has changed as a
34// result of a call to setPixelBuffer().
35//
36// The responsibility for creating and deleting sockets is entirely with the
37// calling code. When VNCServerST wants to close a connection to a client it
38// calls the VNCSConnectionST's close() method which calls shutdown() on the
39// socket. Eventually the calling code will notice that the socket has been
40// shut down and call removeSocket() so that we can delete the
41// VNCSConnectionST. Note that the socket must not be deleted by the calling
42// code until after removeSocket() has been called.
43//
44// One minor complication is that we don't allocate a VNCSConnectionST object
45// for a blacklisted host (since we want to minimise the resources used for
46// dealing with such a connection). In order to properly implement the
47// getSockets function, we must maintain a separate closingSockets list,
48// otherwise blacklisted connections might be "forgotten".
49
50
Pierre Ossman559a2e82012-01-23 15:54:11 +000051#include <assert.h>
Pierre Ossmanf99c5712009-03-13 14:41:27 +000052#include <stdlib.h>
53
Pierre Ossman707fa122015-12-11 20:21:20 +010054#include <rfb/ComparingUpdateTracker.h>
55#include <rfb/KeyRemapper.h>
56#include <rfb/ListConnInfo.h>
57#include <rfb/Security.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000058#include <rfb/ServerCore.h>
59#include <rfb/VNCServerST.h>
60#include <rfb/VNCSConnectionST.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000061#include <rfb/util.h>
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010062#include <rfb/ledStates.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000063
64#include <rdr/types.h>
65
66using namespace rfb;
67
68static LogWriter slog("VNCServerST");
69LogWriter VNCServerST::connectionsLog("Connections");
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000070
71//
72// -=- VNCServerST Implementation
73//
74
75// -=- Constructors/Destructor
76
Adam Tkaca6578bf2010-04-23 14:07:41 +000077VNCServerST::VNCServerST(const char* name_, SDesktop* desktop_)
Pierre Ossman559a2e82012-01-23 15:54:11 +000078 : blHosts(&blacklist), desktop(desktop_), desktopStarted(false),
Pierre Ossmanbb305ca2016-12-11 12:41:26 +010079 blockCounter(0), pb(0), ledState(ledUnknown),
Adam Tkacd36b6262009-09-04 10:57:20 +000080 name(strDup(name_)), pointerClient(0), comparer(0),
Pierre Ossman6a1a0d02017-02-19 15:48:17 +010081 cursor(new Cursor(0, 0, Point(), NULL)),
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000082 renderedCursorInvalid(false),
Pierre Ossmaneef6c9a2018-10-05 17:11:25 +020083 keyRemapper(&KeyRemapper::defInstance),
Pierre Ossmanbbf955e2011-11-08 12:44:10 +000084 lastConnectionTime(0), disableclients(false),
Pierre Ossman6e49e952016-10-07 15:59:38 +020085 frameTimer(this)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000086{
87 lastUserInputTime = lastDisconnectTime = time(0);
88 slog.debug("creating single-threaded server %s", name.buf);
89}
90
91VNCServerST::~VNCServerST()
92{
93 slog.debug("shutting down server %s", name.buf);
94
95 // Close any active clients, with appropriate logging & cleanup
96 closeClients("Server shutdown");
97
Pierre Ossman6e49e952016-10-07 15:59:38 +020098 // Stop trying to render things
99 stopFrameClock();
100
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000101 // Delete all the clients, and their sockets, and any closing sockets
102 // NB: Deleting a client implicitly removes it from the clients list
103 while (!clients.empty()) {
104 delete clients.front();
105 }
106
107 // Stop the desktop object if active, *only* after deleting all clients!
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100108 stopDesktop();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000109
Pierre Ossman05338bc2016-11-08 14:57:11 +0100110 if (comparer)
111 comparer->logStats();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000112 delete comparer;
Pierre Ossman6a1a0d02017-02-19 15:48:17 +0100113
114 delete cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000115}
116
117
118// SocketServer methods
119
120void VNCServerST::addSocket(network::Socket* sock, bool outgoing)
121{
122 // - Check the connection isn't black-marked
123 // *** do this in getSecurity instead?
124 CharArray address(sock->getPeerAddress());
125 if (blHosts->isBlackmarked(address.buf)) {
126 connectionsLog.error("blacklisted: %s", address.buf);
127 try {
128 SConnection::writeConnFailedFromScratch("Too many security failures",
129 &sock->outStream());
130 } catch (rdr::Exception&) {
131 }
132 sock->shutdown();
133 closingSockets.push_back(sock);
134 return;
135 }
136
137 if (clients.empty()) {
138 lastConnectionTime = time(0);
139 }
140
141 VNCSConnectionST* client = new VNCSConnectionST(this, sock, outgoing);
142 client->init();
143}
144
145void VNCServerST::removeSocket(network::Socket* sock) {
146 // - If the socket has resources allocated to it, delete them
147 std::list<VNCSConnectionST*>::iterator ci;
148 for (ci = clients.begin(); ci != clients.end(); ci++) {
149 if ((*ci)->getSock() == sock) {
Pierre Ossmanb6843412018-10-05 17:30:52 +0200150 // - Release the cursor if this client owns it
151 if (pointerClient == *ci)
152 pointerClient = NULL;
153
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000154 // - Delete the per-Socket resources
155 delete *ci;
156
157 // - Check that the desktop object is still required
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100158 if (authClientCount() == 0)
159 stopDesktop();
Pierre Ossman05338bc2016-11-08 14:57:11 +0100160
161 if (comparer)
162 comparer->logStats();
163
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000164 return;
165 }
166 }
167
168 // - If the Socket has no resources, it may have been a closingSocket
169 closingSockets.remove(sock);
170}
171
Pierre Ossmand408ca52016-04-29 14:26:05 +0200172void VNCServerST::processSocketReadEvent(network::Socket* sock)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000173{
174 // - Find the appropriate VNCSConnectionST and process the event
175 std::list<VNCSConnectionST*>::iterator ci;
176 for (ci = clients.begin(); ci != clients.end(); ci++) {
177 if ((*ci)->getSock() == sock) {
178 (*ci)->processMessages();
179 return;
180 }
181 }
182 throw rdr::Exception("invalid Socket in VNCServerST");
183}
184
Pierre Ossmand408ca52016-04-29 14:26:05 +0200185void VNCServerST::processSocketWriteEvent(network::Socket* sock)
186{
187 // - Find the appropriate VNCSConnectionST and process the event
188 std::list<VNCSConnectionST*>::iterator ci;
189 for (ci = clients.begin(); ci != clients.end(); ci++) {
190 if ((*ci)->getSock() == sock) {
191 (*ci)->flushSocket();
192 return;
193 }
194 }
195 throw rdr::Exception("invalid Socket in VNCServerST");
196}
197
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000198int VNCServerST::checkTimeouts()
199{
200 int timeout = 0;
201 std::list<VNCSConnectionST*>::iterator ci, ci_next;
Pierre Ossman2d61deb2011-10-25 15:18:53 +0000202
203 soonestTimeout(&timeout, Timer::checkTimeouts());
204
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000205 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
206 ci_next = ci; ci_next++;
207 soonestTimeout(&timeout, (*ci)->checkIdleTimeout());
208 }
209
210 int timeLeft;
Constantin Kaplinsky8499d0c2008-08-21 05:51:29 +0000211 time_t now = time(0);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000212
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000213 // Check MaxDisconnectionTime
214 if (rfb::Server::maxDisconnectionTime && clients.empty()) {
215 if (now < lastDisconnectTime) {
216 // Someone must have set the time backwards.
217 slog.info("Time has gone backwards - resetting lastDisconnectTime");
218 lastDisconnectTime = now;
219 }
220 timeLeft = lastDisconnectTime + rfb::Server::maxDisconnectionTime - now;
221 if (timeLeft < -60) {
222 // Someone must have set the time forwards.
223 slog.info("Time has gone forwards - resetting lastDisconnectTime");
224 lastDisconnectTime = now;
225 timeLeft = rfb::Server::maxDisconnectionTime;
226 }
227 if (timeLeft <= 0) {
228 slog.info("MaxDisconnectionTime reached, exiting");
229 exit(0);
230 }
231 soonestTimeout(&timeout, timeLeft * 1000);
232 }
233
234 // Check MaxConnectionTime
235 if (rfb::Server::maxConnectionTime && lastConnectionTime && !clients.empty()) {
236 if (now < lastConnectionTime) {
237 // Someone must have set the time backwards.
238 slog.info("Time has gone backwards - resetting lastConnectionTime");
239 lastConnectionTime = now;
240 }
241 timeLeft = lastConnectionTime + rfb::Server::maxConnectionTime - now;
242 if (timeLeft < -60) {
243 // Someone must have set the time forwards.
244 slog.info("Time has gone forwards - resetting lastConnectionTime");
245 lastConnectionTime = now;
246 timeLeft = rfb::Server::maxConnectionTime;
247 }
248 if (timeLeft <= 0) {
249 slog.info("MaxConnectionTime reached, exiting");
250 exit(0);
251 }
252 soonestTimeout(&timeout, timeLeft * 1000);
253 }
254
255
256 // Check MaxIdleTime
257 if (rfb::Server::maxIdleTime) {
258 if (now < lastUserInputTime) {
259 // Someone must have set the time backwards.
260 slog.info("Time has gone backwards - resetting lastUserInputTime");
261 lastUserInputTime = now;
262 }
263 timeLeft = lastUserInputTime + rfb::Server::maxIdleTime - now;
264 if (timeLeft < -60) {
265 // Someone must have set the time forwards.
266 slog.info("Time has gone forwards - resetting lastUserInputTime");
267 lastUserInputTime = now;
268 timeLeft = rfb::Server::maxIdleTime;
269 }
270 if (timeLeft <= 0) {
271 slog.info("MaxIdleTime reached, exiting");
272 exit(0);
273 }
274 soonestTimeout(&timeout, timeLeft * 1000);
275 }
276
277 return timeout;
278}
279
280
281// VNCServer methods
282
Pierre Ossman559a2e82012-01-23 15:54:11 +0000283void VNCServerST::blockUpdates()
284{
285 blockCounter++;
Pierre Ossman6e49e952016-10-07 15:59:38 +0200286
287 stopFrameClock();
Pierre Ossman559a2e82012-01-23 15:54:11 +0000288}
289
290void VNCServerST::unblockUpdates()
291{
292 assert(blockCounter > 0);
293
294 blockCounter--;
295
Pierre Ossman6e49e952016-10-07 15:59:38 +0200296 // Restart the frame clock if we have updates
297 if (blockCounter == 0) {
298 if (!comparer->is_empty())
299 startFrameClock();
300 }
Pierre Ossman559a2e82012-01-23 15:54:11 +0000301}
302
Pierre Ossman04e62db2009-03-23 16:57:07 +0000303void VNCServerST::setPixelBuffer(PixelBuffer* pb_, const ScreenSet& layout)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000304{
Pierre Ossman05338bc2016-11-08 14:57:11 +0100305 if (comparer)
306 comparer->logStats();
307
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000308 pb = pb_;
309 delete comparer;
310 comparer = 0;
311
Pierre Ossman04e62db2009-03-23 16:57:07 +0000312 screenLayout = layout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000313
Pierre Ossman04e62db2009-03-23 16:57:07 +0000314 if (!pb) {
Michal Srb28d570d2017-09-29 14:45:33 +0200315 screenLayout = ScreenSet();
316
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000317 if (desktopStarted)
318 throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
Michal Srb28d570d2017-09-29 14:45:33 +0200319
Pierre Ossman04e62db2009-03-23 16:57:07 +0000320 return;
321 }
322
Pierre Ossman6cd61172018-05-07 14:24:56 +0200323 // Assume the framebuffer contents wasn't saved and reset everything
324 // that tracks its contents
Pierre Ossman04e62db2009-03-23 16:57:07 +0000325 comparer = new ComparingUpdateTracker(pb);
Pierre Ossman6ea6e1a2014-02-12 16:33:43 +0100326 renderedCursorInvalid = true;
Pierre Ossman6cd61172018-05-07 14:24:56 +0200327 add_changed(pb->getRect());
Pierre Ossman04e62db2009-03-23 16:57:07 +0000328
329 // Make sure that we have at least one screen
330 if (screenLayout.num_screens() == 0)
331 screenLayout.add_screen(Screen(0, 0, 0, pb->width(), pb->height(), 0));
332
333 std::list<VNCSConnectionST*>::iterator ci, ci_next;
334 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
335 ci_next = ci; ci_next++;
336 (*ci)->pixelBufferChange();
337 // Since the new pixel buffer means an ExtendedDesktopSize needs to
338 // be sent anyway, we don't need to call screenLayoutChange.
339 }
340}
341
342void VNCServerST::setPixelBuffer(PixelBuffer* pb_)
343{
Michal Srb28d570d2017-09-29 14:45:33 +0200344 ScreenSet layout = screenLayout;
Pierre Ossman04e62db2009-03-23 16:57:07 +0000345
346 // Check that the screen layout is still valid
Michal Srb28d570d2017-09-29 14:45:33 +0200347 if (pb_ && !layout.validate(pb_->width(), pb_->height())) {
Pierre Ossman04e62db2009-03-23 16:57:07 +0000348 Rect fbRect;
349 ScreenSet::iterator iter, iter_next;
350
351 fbRect.setXYWH(0, 0, pb_->width(), pb_->height());
352
353 for (iter = layout.begin();iter != layout.end();iter = iter_next) {
354 iter_next = iter; ++iter_next;
355 if (iter->dimensions.enclosed_by(fbRect))
356 continue;
357 iter->dimensions = iter->dimensions.intersect(fbRect);
358 if (iter->dimensions.is_empty()) {
359 slog.info("Removing screen %d (%x) as it is completely outside the new framebuffer",
360 (int)iter->id, (unsigned)iter->id);
361 layout.remove_screen(iter->id);
362 }
363 }
364 }
365
366 setPixelBuffer(pb_, layout);
367}
368
369void VNCServerST::setScreenLayout(const ScreenSet& layout)
370{
371 if (!pb)
372 throw Exception("setScreenLayout: new screen layout without a PixelBuffer");
373 if (!layout.validate(pb->width(), pb->height()))
374 throw Exception("setScreenLayout: invalid screen layout");
375
Pierre Ossmandf453202009-04-02 14:26:45 +0000376 screenLayout = layout;
377
Pierre Ossman04e62db2009-03-23 16:57:07 +0000378 std::list<VNCSConnectionST*>::iterator ci, ci_next;
379 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
380 ci_next = ci; ci_next++;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000381 (*ci)->screenLayoutChangeOrClose(reasonServer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000382 }
383}
384
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000385void VNCServerST::bell()
386{
387 std::list<VNCSConnectionST*>::iterator ci, ci_next;
388 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
389 ci_next = ci; ci_next++;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000390 (*ci)->bellOrClose();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000391 }
392}
393
394void VNCServerST::serverCutText(const char* str, int len)
395{
396 std::list<VNCSConnectionST*>::iterator ci, ci_next;
397 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
398 ci_next = ci; ci_next++;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000399 (*ci)->serverCutTextOrClose(str, len);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000400 }
401}
402
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000403void VNCServerST::setName(const char* name_)
404{
Adam Tkacd36b6262009-09-04 10:57:20 +0000405 name.replaceBuf(strDup(name_));
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000406 std::list<VNCSConnectionST*>::iterator ci, ci_next;
407 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
408 ci_next = ci; ci_next++;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000409 (*ci)->setDesktopNameOrClose(name_);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000410 }
411}
412
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000413void VNCServerST::add_changed(const Region& region)
414{
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000415 if (comparer == NULL)
416 return;
417
418 comparer->add_changed(region);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200419 startFrameClock();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000420}
421
422void VNCServerST::add_copied(const Region& dest, const Point& delta)
423{
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000424 if (comparer == NULL)
425 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000426
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000427 comparer->add_copied(dest, delta);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200428 startFrameClock();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000429}
430
431void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
Pierre Ossman6a1a0d02017-02-19 15:48:17 +0100432 const rdr::U8* data)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000433{
Pierre Ossman6a1a0d02017-02-19 15:48:17 +0100434 delete cursor;
435 cursor = new Cursor(width, height, newHotspot, data);
436 cursor->crop();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000437
438 renderedCursorInvalid = true;
439
440 std::list<VNCSConnectionST*>::iterator ci, ci_next;
441 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
442 ci_next = ci; ci_next++;
443 (*ci)->renderedCursorChange();
444 (*ci)->setCursorOrClose();
445 }
446}
447
448void VNCServerST::setCursorPos(const Point& pos)
449{
450 if (!cursorPos.equals(pos)) {
451 cursorPos = pos;
452 renderedCursorInvalid = true;
453 std::list<VNCSConnectionST*>::iterator ci;
454 for (ci = clients.begin(); ci != clients.end(); ci++)
455 (*ci)->renderedCursorChange();
456 }
457}
458
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100459void VNCServerST::setLEDState(unsigned int state)
460{
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100461 std::list<VNCSConnectionST*>::iterator ci, ci_next;
462
463 if (state == ledState)
464 return;
465
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100466 ledState = state;
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100467
468 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
469 ci_next = ci; ci_next++;
470 (*ci)->setLEDStateOrClose(state);
471 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100472}
473
Pierre Ossmanb6843412018-10-05 17:30:52 +0200474// Event handlers
475
476void VNCServerST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down)
477{
478 lastUserInputTime = time(0);
479
480 // Remap the key if required
481 if (keyRemapper) {
482 rdr::U32 newkey;
483 newkey = keyRemapper->remapKey(keysym);
484 if (newkey != keysym) {
485 slog.debug("Key remapped to 0x%x", newkey);
486 keysym = newkey;
487 }
488 }
489
490 desktop->keyEvent(keysym, keycode, down);
491}
492
493void VNCServerST::pointerEvent(VNCSConnectionST* client,
494 const Point& pos, int buttonMask)
495{
496 lastUserInputTime = time(0);
497
498 // Let one client own the cursor whilst buttons are pressed in order
499 // to provide a bit more sane user experience
500 if ((pointerClient != NULL) && (pointerClient != client))
501 return;
502
503 if (buttonMask)
504 pointerClient = client;
505 else
506 pointerClient = NULL;
507
508 desktop->pointerEvent(pos, buttonMask);
509}
510
511void VNCServerST::clientCutText(const char* str, int len)
512{
513 desktop->clientCutText(str, len);
514}
515
Pierre Ossman07e44cc2018-10-05 17:32:57 +0200516unsigned int VNCServerST::setDesktopSize(VNCSConnectionST* requester,
517 int fb_width, int fb_height,
518 const ScreenSet& layout)
519{
520 unsigned int result;
521 std::list<VNCSConnectionST*>::iterator ci, ci_next;
522
523 // Don't bother the desktop with an invalid configuration
524 if (!layout.validate(fb_width, fb_height))
525 return resultInvalid;
526
527 // FIXME: the desktop will call back to VNCServerST and an extra set
528 // of ExtendedDesktopSize messages will be sent. This is okay
529 // protocol-wise, but unnecessary.
530 result = desktop->setScreenLayout(fb_width, fb_height, layout);
531 if (result != resultSuccess)
532 return result;
533
534 // Sanity check
535 if (screenLayout != layout)
536 throw Exception("Desktop configured a different screen layout than requested");
537
538 // Notify other clients
539 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
540 ci_next = ci; ci_next++;
541 if ((*ci) == requester)
542 continue;
543 (*ci)->screenLayoutChangeOrClose(reasonOtherClient);
544 }
545
546 return resultSuccess;
547}
548
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000549// Other public methods
550
551void VNCServerST::approveConnection(network::Socket* sock, bool accept,
552 const char* reason)
553{
554 std::list<VNCSConnectionST*>::iterator ci;
555 for (ci = clients.begin(); ci != clients.end(); ci++) {
556 if ((*ci)->getSock() == sock) {
557 (*ci)->approveConnectionOrClose(accept, reason);
558 return;
559 }
560 }
561}
562
563void VNCServerST::closeClients(const char* reason, network::Socket* except)
564{
565 std::list<VNCSConnectionST*>::iterator i, next_i;
566 for (i=clients.begin(); i!=clients.end(); i=next_i) {
567 next_i = i; next_i++;
568 if ((*i)->getSock() != except)
569 (*i)->close(reason);
570 }
571}
572
573void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
574{
575 sockets->clear();
576 std::list<VNCSConnectionST*>::iterator ci;
577 for (ci = clients.begin(); ci != clients.end(); ci++) {
578 sockets->push_back((*ci)->getSock());
579 }
580 std::list<network::Socket*>::iterator si;
581 for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
582 sockets->push_back(*si);
583 }
584}
585
586SConnection* VNCServerST::getSConnection(network::Socket* sock) {
587 std::list<VNCSConnectionST*>::iterator ci;
588 for (ci = clients.begin(); ci != clients.end(); ci++) {
589 if ((*ci)->getSock() == sock)
590 return *ci;
591 }
592 return 0;
593}
594
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000595bool VNCServerST::handleTimeout(Timer* t)
596{
Pierre Ossman6e49e952016-10-07 15:59:38 +0200597 if (t == &frameTimer) {
598 // We keep running until we go a full interval without any updates
599 if (comparer->is_empty())
600 return false;
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000601
Pierre Ossman6e49e952016-10-07 15:59:38 +0200602 writeUpdate();
Pierre Ossman7be73d72017-11-06 13:16:35 +0100603
604 // If this is the first iteration then we need to adjust the timeout
605 if (frameTimer.getTimeoutMs() != 1000/rfb::Server::frameRate) {
606 frameTimer.start(1000/rfb::Server::frameRate);
607 return false;
608 }
609
Pierre Ossman6e49e952016-10-07 15:59:38 +0200610 return true;
611 }
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000612
613 return false;
614}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000615
Pierre Ossmaneef6c9a2018-10-05 17:11:25 +0200616void VNCServerST::queryConnection(network::Socket* sock,
617 const char* userName)
618{
619 desktop->queryConnection(sock, userName);
620}
621
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000622// -=- Internal methods
623
624void VNCServerST::startDesktop()
625{
626 if (!desktopStarted) {
627 slog.debug("starting desktop");
628 desktop->start(this);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000629 if (!pb)
630 throw Exception("SDesktop::start() did not set a valid PixelBuffer");
Pierre Ossman6cd61172018-05-07 14:24:56 +0200631 desktopStarted = true;
632 // The tracker might have accumulated changes whilst we were
633 // stopped, so flush those out
634 if (!comparer->is_empty())
635 writeUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000636 }
637}
638
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100639void VNCServerST::stopDesktop()
640{
641 if (desktopStarted) {
642 slog.debug("stopping desktop");
643 desktopStarted = false;
644 desktop->stop();
645 stopFrameClock();
646 }
647}
648
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000649int VNCServerST::authClientCount() {
650 int count = 0;
651 std::list<VNCSConnectionST*>::iterator ci;
652 for (ci = clients.begin(); ci != clients.end(); ci++) {
653 if ((*ci)->authenticated())
654 count++;
655 }
656 return count;
657}
658
659inline bool VNCServerST::needRenderedCursor()
660{
661 std::list<VNCSConnectionST*>::iterator ci;
662 for (ci = clients.begin(); ci != clients.end(); ci++)
663 if ((*ci)->needRenderedCursor()) return true;
664 return false;
665}
666
Pierre Ossman6e49e952016-10-07 15:59:38 +0200667void VNCServerST::startFrameClock()
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000668{
Pierre Ossman6e49e952016-10-07 15:59:38 +0200669 if (frameTimer.isStarted())
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000670 return;
Pierre Ossman559a2e82012-01-23 15:54:11 +0000671 if (blockCounter > 0)
672 return;
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100673 if (!desktopStarted)
674 return;
Pierre Ossman559a2e82012-01-23 15:54:11 +0000675
Pierre Ossman7be73d72017-11-06 13:16:35 +0100676 // The first iteration will be just half a frame as we get a very
677 // unstable update rate if we happen to be perfectly in sync with
678 // the application's update rate
679 frameTimer.start(1000/rfb::Server::frameRate/2);
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000680}
681
Pierre Ossman6e49e952016-10-07 15:59:38 +0200682void VNCServerST::stopFrameClock()
683{
684 frameTimer.stop();
685}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000686
Pierre Ossmana2b80d62018-03-23 09:30:09 +0100687int VNCServerST::msToNextUpdate()
688{
689 // FIXME: If the application is updating slower than frameRate then
690 // we could allow the clients more time here
691
692 if (!frameTimer.isStarted())
693 return 1000/rfb::Server::frameRate/2;
694 else
695 return frameTimer.getRemainingMs();
696}
697
Pierre Ossman6e49e952016-10-07 15:59:38 +0200698// writeUpdate() is called on a regular interval in order to see what
699// updates are pending and propagates them to the update tracker for
700// each client. It uses the ComparingUpdateTracker's compare() method
701// to filter out areas of the screen which haven't actually changed. It
702// also checks the state of the (server-side) rendered cursor, if
703// necessary rendering it again with the correct background.
704
705void VNCServerST::writeUpdate()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000706{
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000707 UpdateInfo ui;
Pierre Ossman6e49e952016-10-07 15:59:38 +0200708 Region toCheck;
709
710 std::list<VNCSConnectionST*>::iterator ci, ci_next;
711
712 assert(blockCounter == 0);
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100713 assert(desktopStarted);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200714
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000715 comparer->getUpdateInfo(&ui, pb->getRect());
Pierre Ossman6e49e952016-10-07 15:59:38 +0200716 toCheck = ui.changed.union_(ui.copied);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000717
Pierre Ossman6e49e952016-10-07 15:59:38 +0200718 if (needRenderedCursor()) {
Pierre Ossman6a1a0d02017-02-19 15:48:17 +0100719 Rect clippedCursorRect = Rect(0, 0, cursor->width(), cursor->height())
720 .translate(cursorPos.subtract(cursor->hotspot()))
721 .intersect(pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000722
Pierre Ossman24684e52016-12-05 16:58:19 +0100723 if (!toCheck.intersect(clippedCursorRect).is_empty())
724 renderedCursorInvalid = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000725 }
726
727 pb->grabRegion(toCheck);
728
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000729 if (getComparerState())
730 comparer->enable();
731 else
732 comparer->disable();
733
734 if (comparer->compare())
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000735 comparer->getUpdateInfo(&ui, pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000736
Pierre Ossman6e49e952016-10-07 15:59:38 +0200737 comparer->clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000738
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000739 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
740 ci_next = ci; ci_next++;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000741 (*ci)->add_copied(ui.copied, ui.copy_delta);
742 (*ci)->add_changed(ui.changed);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200743 (*ci)->writeFramebufferUpdateOrClose();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000744 }
Pierre Ossman6e49e952016-10-07 15:59:38 +0200745}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000746
Pierre Ossman6e49e952016-10-07 15:59:38 +0200747// checkUpdate() is called by clients to see if it is safe to read from
748// the framebuffer at this time.
749
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100750Region VNCServerST::getPendingRegion()
Pierre Ossman6e49e952016-10-07 15:59:38 +0200751{
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100752 UpdateInfo ui;
753
Pierre Ossman6e49e952016-10-07 15:59:38 +0200754 // Block clients as the frame buffer cannot be safely accessed
755 if (blockCounter > 0)
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100756 return pb->getRect();
Pierre Ossman6e49e952016-10-07 15:59:38 +0200757
758 // Block client from updating if there are pending updates
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100759 if (comparer->is_empty())
760 return Region();
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000761
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100762 comparer->getUpdateInfo(&ui, pb->getRect());
763
764 return ui.changed.union_(ui.copied);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000765}
766
Pierre Ossman24684e52016-12-05 16:58:19 +0100767const RenderedCursor* VNCServerST::getRenderedCursor()
768{
769 if (renderedCursorInvalid) {
Pierre Ossman7cb4f312017-02-24 13:25:00 +0100770 renderedCursor.update(pb, cursor, cursorPos);
Pierre Ossman24684e52016-12-05 16:58:19 +0100771 renderedCursorInvalid = false;
772 }
773
774 return &renderedCursor;
775}
776
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000777void VNCServerST::getConnInfo(ListConnInfo * listConn)
778{
779 listConn->Clear();
780 listConn->setDisable(getDisable());
781 if (clients.empty())
782 return;
783 std::list<VNCSConnectionST*>::iterator i;
784 for (i = clients.begin(); i != clients.end(); i++)
785 listConn->addInfo((void*)(*i), (*i)->getSock()->getPeerAddress(),
786 (*i)->getStartTime(), (*i)->getStatus());
787}
788
789void VNCServerST::setConnStatus(ListConnInfo* listConn)
790{
791 setDisable(listConn->getDisable());
792 if (listConn->Empty() || clients.empty()) return;
793 for (listConn->iBegin(); !listConn->iEnd(); listConn->iNext()) {
794 VNCSConnectionST* conn = (VNCSConnectionST*)listConn->iGetConn();
795 std::list<VNCSConnectionST*>::iterator i;
796 for (i = clients.begin(); i != clients.end(); i++) {
797 if ((*i) == conn) {
798 int status = listConn->iGetStatus();
799 if (status == 3) {
800 (*i)->close(0);
801 } else {
802 (*i)->setStatus(status);
803 }
804 break;
805 }
806 }
807 }
808}
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000809
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000810bool VNCServerST::getComparerState()
811{
812 if (rfb::Server::compareFB == 0)
813 return false;
814 if (rfb::Server::compareFB != 2)
815 return true;
816
817 std::list<VNCSConnectionST*>::iterator ci, ci_next;
818 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
819 ci_next = ci; ci_next++;
820 if ((*ci)->getComparerState())
821 return true;
822 }
823 return false;
824}