blob: 352b80f225a7a160134a95a41820a74178adfec1 [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>
Pierre Ossman6c97fa42018-10-05 17:35:51 +020056#include <rfb/LogWriter.h>
Pierre Ossman707fa122015-12-11 20:21:20 +010057#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");
Pierre Ossman6c97fa42018-10-05 17:35:51 +020069static LogWriter 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 Ossmanf43137c2018-10-26 15:34:03 +020084 idleTimer(this), disconnectTimer(this), connectTimer(this),
85 frameTimer(this)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000086{
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000087 slog.debug("creating single-threaded server %s", name.buf);
Pierre Ossmanf43137c2018-10-26 15:34:03 +020088
89 // FIXME: Do we really want to kick off these right away?
90 if (rfb::Server::maxIdleTime)
91 idleTimer.start(secsToMillis(rfb::Server::maxIdleTime));
92 if (rfb::Server::maxDisconnectionTime)
93 disconnectTimer.start(secsToMillis(rfb::Server::maxDisconnectionTime));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000094}
95
96VNCServerST::~VNCServerST()
97{
98 slog.debug("shutting down server %s", name.buf);
99
100 // Close any active clients, with appropriate logging & cleanup
101 closeClients("Server shutdown");
102
Pierre Ossman6e49e952016-10-07 15:59:38 +0200103 // Stop trying to render things
104 stopFrameClock();
105
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000106 // Delete all the clients, and their sockets, and any closing sockets
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000107 while (!clients.empty()) {
Pierre Ossman6c97fa42018-10-05 17:35:51 +0200108 VNCSConnectionST* client;
109 client = clients.front();
110 clients.pop_front();
111 delete client;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000112 }
113
114 // Stop the desktop object if active, *only* after deleting all clients!
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100115 stopDesktop();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000116
Pierre Ossman05338bc2016-11-08 14:57:11 +0100117 if (comparer)
118 comparer->logStats();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000119 delete comparer;
Pierre Ossman6a1a0d02017-02-19 15:48:17 +0100120
121 delete cursor;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000122}
123
124
125// SocketServer methods
126
127void VNCServerST::addSocket(network::Socket* sock, bool outgoing)
128{
129 // - Check the connection isn't black-marked
130 // *** do this in getSecurity instead?
131 CharArray address(sock->getPeerAddress());
132 if (blHosts->isBlackmarked(address.buf)) {
133 connectionsLog.error("blacklisted: %s", address.buf);
134 try {
Pierre Ossman4bba2462018-10-11 07:52:50 +0200135 rdr::OutStream& os = sock->outStream();
136
137 // Shortest possible way to tell a client it is not welcome
138 os.writeBytes("RFB 003.003\n", 12);
139 os.writeU32(0);
140 os.writeString("Too many security failures");
141 os.flush();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000142 } catch (rdr::Exception&) {
143 }
144 sock->shutdown();
145 closingSockets.push_back(sock);
146 return;
147 }
148
Pierre Ossman6c97fa42018-10-05 17:35:51 +0200149 CharArray name;
150 name.buf = sock->getPeerEndpoint();
151 connectionsLog.status("accepted: %s", name.buf);
152
Pierre Ossmanf43137c2018-10-26 15:34:03 +0200153 // Adjust the exit timers
154 if (rfb::Server::maxConnectionTime && clients.empty())
155 connectTimer.start(secsToMillis(rfb::Server::maxConnectionTime));
156 disconnectTimer.stop();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000157
158 VNCSConnectionST* client = new VNCSConnectionST(this, sock, outgoing);
Pierre Ossman6c97fa42018-10-05 17:35:51 +0200159 clients.push_front(client);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000160 client->init();
161}
162
163void VNCServerST::removeSocket(network::Socket* sock) {
164 // - If the socket has resources allocated to it, delete them
165 std::list<VNCSConnectionST*>::iterator ci;
166 for (ci = clients.begin(); ci != clients.end(); ci++) {
167 if ((*ci)->getSock() == sock) {
Pierre Ossman6c97fa42018-10-05 17:35:51 +0200168 clients.remove(*ci);
169
Pierre Ossmanb6843412018-10-05 17:30:52 +0200170 // - Release the cursor if this client owns it
171 if (pointerClient == *ci)
172 pointerClient = NULL;
173
Pierre Ossmanf43137c2018-10-26 15:34:03 +0200174 // Adjust the exit timers
175 connectTimer.stop();
176 if (rfb::Server::maxDisconnectionTime && clients.empty())
177 disconnectTimer.start(secsToMillis(rfb::Server::maxDisconnectionTime));
Pierre Ossman6c97fa42018-10-05 17:35:51 +0200178
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000179 // - Delete the per-Socket resources
180 delete *ci;
181
Pierre Ossman6c97fa42018-10-05 17:35:51 +0200182 CharArray name;
183 name.buf = sock->getPeerEndpoint();
184 connectionsLog.status("closed: %s", name.buf);
185
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000186 // - Check that the desktop object is still required
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100187 if (authClientCount() == 0)
188 stopDesktop();
Pierre Ossman05338bc2016-11-08 14:57:11 +0100189
190 if (comparer)
191 comparer->logStats();
192
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000193 return;
194 }
195 }
196
197 // - If the Socket has no resources, it may have been a closingSocket
198 closingSockets.remove(sock);
199}
200
Pierre Ossmand408ca52016-04-29 14:26:05 +0200201void VNCServerST::processSocketReadEvent(network::Socket* sock)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000202{
203 // - Find the appropriate VNCSConnectionST and process the event
204 std::list<VNCSConnectionST*>::iterator ci;
205 for (ci = clients.begin(); ci != clients.end(); ci++) {
206 if ((*ci)->getSock() == sock) {
207 (*ci)->processMessages();
208 return;
209 }
210 }
211 throw rdr::Exception("invalid Socket in VNCServerST");
212}
213
Pierre Ossmand408ca52016-04-29 14:26:05 +0200214void VNCServerST::processSocketWriteEvent(network::Socket* sock)
215{
216 // - Find the appropriate VNCSConnectionST and process the event
217 std::list<VNCSConnectionST*>::iterator ci;
218 for (ci = clients.begin(); ci != clients.end(); ci++) {
219 if ((*ci)->getSock() == sock) {
220 (*ci)->flushSocket();
221 return;
222 }
223 }
224 throw rdr::Exception("invalid Socket in VNCServerST");
225}
226
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000227int VNCServerST::checkTimeouts()
228{
229 int timeout = 0;
230 std::list<VNCSConnectionST*>::iterator ci, ci_next;
Pierre Ossman2d61deb2011-10-25 15:18:53 +0000231
232 soonestTimeout(&timeout, Timer::checkTimeouts());
233
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000234 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
235 ci_next = ci; ci_next++;
236 soonestTimeout(&timeout, (*ci)->checkIdleTimeout());
237 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000238
239 return timeout;
240}
241
242
243// VNCServer methods
244
Pierre Ossman559a2e82012-01-23 15:54:11 +0000245void VNCServerST::blockUpdates()
246{
247 blockCounter++;
Pierre Ossman6e49e952016-10-07 15:59:38 +0200248
249 stopFrameClock();
Pierre Ossman559a2e82012-01-23 15:54:11 +0000250}
251
252void VNCServerST::unblockUpdates()
253{
254 assert(blockCounter > 0);
255
256 blockCounter--;
257
Pierre Ossman6e49e952016-10-07 15:59:38 +0200258 // Restart the frame clock if we have updates
259 if (blockCounter == 0) {
260 if (!comparer->is_empty())
261 startFrameClock();
262 }
Pierre Ossman559a2e82012-01-23 15:54:11 +0000263}
264
Pierre Ossman04e62db2009-03-23 16:57:07 +0000265void VNCServerST::setPixelBuffer(PixelBuffer* pb_, const ScreenSet& layout)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000266{
Pierre Ossman05338bc2016-11-08 14:57:11 +0100267 if (comparer)
268 comparer->logStats();
269
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000270 pb = pb_;
271 delete comparer;
272 comparer = 0;
273
Pierre Ossman04e62db2009-03-23 16:57:07 +0000274 screenLayout = layout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000275
Pierre Ossman04e62db2009-03-23 16:57:07 +0000276 if (!pb) {
Michal Srb28d570d2017-09-29 14:45:33 +0200277 screenLayout = ScreenSet();
278
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000279 if (desktopStarted)
280 throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
Michal Srb28d570d2017-09-29 14:45:33 +0200281
Pierre Ossman04e62db2009-03-23 16:57:07 +0000282 return;
283 }
284
Pierre Ossman6cd61172018-05-07 14:24:56 +0200285 // Assume the framebuffer contents wasn't saved and reset everything
286 // that tracks its contents
Pierre Ossman04e62db2009-03-23 16:57:07 +0000287 comparer = new ComparingUpdateTracker(pb);
Pierre Ossman6ea6e1a2014-02-12 16:33:43 +0100288 renderedCursorInvalid = true;
Pierre Ossman6cd61172018-05-07 14:24:56 +0200289 add_changed(pb->getRect());
Pierre Ossman04e62db2009-03-23 16:57:07 +0000290
291 // Make sure that we have at least one screen
292 if (screenLayout.num_screens() == 0)
293 screenLayout.add_screen(Screen(0, 0, 0, pb->width(), pb->height(), 0));
294
295 std::list<VNCSConnectionST*>::iterator ci, ci_next;
296 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
297 ci_next = ci; ci_next++;
298 (*ci)->pixelBufferChange();
299 // Since the new pixel buffer means an ExtendedDesktopSize needs to
300 // be sent anyway, we don't need to call screenLayoutChange.
301 }
302}
303
304void VNCServerST::setPixelBuffer(PixelBuffer* pb_)
305{
Michal Srb28d570d2017-09-29 14:45:33 +0200306 ScreenSet layout = screenLayout;
Pierre Ossman04e62db2009-03-23 16:57:07 +0000307
308 // Check that the screen layout is still valid
Michal Srb28d570d2017-09-29 14:45:33 +0200309 if (pb_ && !layout.validate(pb_->width(), pb_->height())) {
Pierre Ossman04e62db2009-03-23 16:57:07 +0000310 Rect fbRect;
311 ScreenSet::iterator iter, iter_next;
312
313 fbRect.setXYWH(0, 0, pb_->width(), pb_->height());
314
315 for (iter = layout.begin();iter != layout.end();iter = iter_next) {
316 iter_next = iter; ++iter_next;
317 if (iter->dimensions.enclosed_by(fbRect))
318 continue;
319 iter->dimensions = iter->dimensions.intersect(fbRect);
320 if (iter->dimensions.is_empty()) {
321 slog.info("Removing screen %d (%x) as it is completely outside the new framebuffer",
322 (int)iter->id, (unsigned)iter->id);
323 layout.remove_screen(iter->id);
324 }
325 }
326 }
327
328 setPixelBuffer(pb_, layout);
329}
330
331void VNCServerST::setScreenLayout(const ScreenSet& layout)
332{
333 if (!pb)
334 throw Exception("setScreenLayout: new screen layout without a PixelBuffer");
335 if (!layout.validate(pb->width(), pb->height()))
336 throw Exception("setScreenLayout: invalid screen layout");
337
Pierre Ossmandf453202009-04-02 14:26:45 +0000338 screenLayout = layout;
339
Pierre Ossman04e62db2009-03-23 16:57:07 +0000340 std::list<VNCSConnectionST*>::iterator ci, ci_next;
341 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
342 ci_next = ci; ci_next++;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000343 (*ci)->screenLayoutChangeOrClose(reasonServer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000344 }
345}
346
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000347void VNCServerST::bell()
348{
349 std::list<VNCSConnectionST*>::iterator ci, ci_next;
350 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
351 ci_next = ci; ci_next++;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000352 (*ci)->bellOrClose();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000353 }
354}
355
356void VNCServerST::serverCutText(const char* str, int len)
357{
358 std::list<VNCSConnectionST*>::iterator ci, ci_next;
359 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
360 ci_next = ci; ci_next++;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000361 (*ci)->serverCutTextOrClose(str, len);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000362 }
363}
364
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000365void VNCServerST::setName(const char* name_)
366{
Adam Tkacd36b6262009-09-04 10:57:20 +0000367 name.replaceBuf(strDup(name_));
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000368 std::list<VNCSConnectionST*>::iterator ci, ci_next;
369 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
370 ci_next = ci; ci_next++;
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000371 (*ci)->setDesktopNameOrClose(name_);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000372 }
373}
374
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000375void VNCServerST::add_changed(const Region& region)
376{
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000377 if (comparer == NULL)
378 return;
379
380 comparer->add_changed(region);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200381 startFrameClock();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000382}
383
384void VNCServerST::add_copied(const Region& dest, const Point& delta)
385{
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000386 if (comparer == NULL)
387 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000388
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000389 comparer->add_copied(dest, delta);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200390 startFrameClock();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000391}
392
393void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
Pierre Ossman6a1a0d02017-02-19 15:48:17 +0100394 const rdr::U8* data)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000395{
Pierre Ossman6a1a0d02017-02-19 15:48:17 +0100396 delete cursor;
397 cursor = new Cursor(width, height, newHotspot, data);
398 cursor->crop();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000399
400 renderedCursorInvalid = true;
401
402 std::list<VNCSConnectionST*>::iterator ci, ci_next;
403 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
404 ci_next = ci; ci_next++;
405 (*ci)->renderedCursorChange();
406 (*ci)->setCursorOrClose();
407 }
408}
409
410void VNCServerST::setCursorPos(const Point& pos)
411{
412 if (!cursorPos.equals(pos)) {
413 cursorPos = pos;
414 renderedCursorInvalid = true;
415 std::list<VNCSConnectionST*>::iterator ci;
416 for (ci = clients.begin(); ci != clients.end(); ci++)
417 (*ci)->renderedCursorChange();
418 }
419}
420
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100421void VNCServerST::setLEDState(unsigned int state)
422{
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100423 std::list<VNCSConnectionST*>::iterator ci, ci_next;
424
425 if (state == ledState)
426 return;
427
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100428 ledState = state;
Pierre Ossmanb45a84f2016-12-12 16:59:15 +0100429
430 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
431 ci_next = ci; ci_next++;
432 (*ci)->setLEDStateOrClose(state);
433 }
Pierre Ossmanbb305ca2016-12-11 12:41:26 +0100434}
435
Pierre Ossmanb6843412018-10-05 17:30:52 +0200436// Event handlers
437
438void VNCServerST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down)
439{
Pierre Ossmanf43137c2018-10-26 15:34:03 +0200440 if (rfb::Server::maxIdleTime)
441 idleTimer.start(secsToMillis(rfb::Server::maxIdleTime));
Pierre Ossmanb6843412018-10-05 17:30:52 +0200442
443 // Remap the key if required
444 if (keyRemapper) {
445 rdr::U32 newkey;
446 newkey = keyRemapper->remapKey(keysym);
447 if (newkey != keysym) {
448 slog.debug("Key remapped to 0x%x", newkey);
449 keysym = newkey;
450 }
451 }
452
453 desktop->keyEvent(keysym, keycode, down);
454}
455
456void VNCServerST::pointerEvent(VNCSConnectionST* client,
457 const Point& pos, int buttonMask)
458{
Pierre Ossmanf43137c2018-10-26 15:34:03 +0200459 if (rfb::Server::maxIdleTime)
460 idleTimer.start(secsToMillis(rfb::Server::maxIdleTime));
Pierre Ossmanb6843412018-10-05 17:30:52 +0200461
462 // Let one client own the cursor whilst buttons are pressed in order
463 // to provide a bit more sane user experience
464 if ((pointerClient != NULL) && (pointerClient != client))
465 return;
466
467 if (buttonMask)
468 pointerClient = client;
469 else
470 pointerClient = NULL;
471
472 desktop->pointerEvent(pos, buttonMask);
473}
474
475void VNCServerST::clientCutText(const char* str, int len)
476{
477 desktop->clientCutText(str, len);
478}
479
Pierre Ossman07e44cc2018-10-05 17:32:57 +0200480unsigned int VNCServerST::setDesktopSize(VNCSConnectionST* requester,
481 int fb_width, int fb_height,
482 const ScreenSet& layout)
483{
484 unsigned int result;
485 std::list<VNCSConnectionST*>::iterator ci, ci_next;
486
487 // Don't bother the desktop with an invalid configuration
488 if (!layout.validate(fb_width, fb_height))
489 return resultInvalid;
490
491 // FIXME: the desktop will call back to VNCServerST and an extra set
492 // of ExtendedDesktopSize messages will be sent. This is okay
493 // protocol-wise, but unnecessary.
494 result = desktop->setScreenLayout(fb_width, fb_height, layout);
495 if (result != resultSuccess)
496 return result;
497
498 // Sanity check
499 if (screenLayout != layout)
500 throw Exception("Desktop configured a different screen layout than requested");
501
502 // Notify other clients
503 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
504 ci_next = ci; ci_next++;
505 if ((*ci) == requester)
506 continue;
507 (*ci)->screenLayoutChangeOrClose(reasonOtherClient);
508 }
509
510 return resultSuccess;
511}
512
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000513// Other public methods
514
515void VNCServerST::approveConnection(network::Socket* sock, bool accept,
516 const char* reason)
517{
518 std::list<VNCSConnectionST*>::iterator ci;
519 for (ci = clients.begin(); ci != clients.end(); ci++) {
520 if ((*ci)->getSock() == sock) {
521 (*ci)->approveConnectionOrClose(accept, reason);
522 return;
523 }
524 }
525}
526
527void VNCServerST::closeClients(const char* reason, network::Socket* except)
528{
529 std::list<VNCSConnectionST*>::iterator i, next_i;
530 for (i=clients.begin(); i!=clients.end(); i=next_i) {
531 next_i = i; next_i++;
532 if ((*i)->getSock() != except)
533 (*i)->close(reason);
534 }
535}
536
537void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
538{
539 sockets->clear();
540 std::list<VNCSConnectionST*>::iterator ci;
541 for (ci = clients.begin(); ci != clients.end(); ci++) {
542 sockets->push_back((*ci)->getSock());
543 }
544 std::list<network::Socket*>::iterator si;
545 for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
546 sockets->push_back(*si);
547 }
548}
549
Pierre Ossman7d64b332018-10-08 15:59:02 +0200550SConnection* VNCServerST::getConnection(network::Socket* sock) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000551 std::list<VNCSConnectionST*>::iterator ci;
552 for (ci = clients.begin(); ci != clients.end(); ci++) {
553 if ((*ci)->getSock() == sock)
554 return *ci;
555 }
556 return 0;
557}
558
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000559bool VNCServerST::handleTimeout(Timer* t)
560{
Pierre Ossman6e49e952016-10-07 15:59:38 +0200561 if (t == &frameTimer) {
562 // We keep running until we go a full interval without any updates
563 if (comparer->is_empty())
564 return false;
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000565
Pierre Ossman6e49e952016-10-07 15:59:38 +0200566 writeUpdate();
Pierre Ossman7be73d72017-11-06 13:16:35 +0100567
568 // If this is the first iteration then we need to adjust the timeout
569 if (frameTimer.getTimeoutMs() != 1000/rfb::Server::frameRate) {
570 frameTimer.start(1000/rfb::Server::frameRate);
571 return false;
572 }
573
Pierre Ossman6e49e952016-10-07 15:59:38 +0200574 return true;
Pierre Ossmanf43137c2018-10-26 15:34:03 +0200575 } else if (t == &idleTimer) {
576 slog.info("MaxIdleTime reached, exiting");
577 exit(0);
578 } else if (t == &disconnectTimer) {
579 slog.info("MaxDisconnectionTime reached, exiting");
580 exit(0);
581 } else if (t == &connectTimer) {
582 slog.info("MaxConnectionTime reached, exiting");
583 exit(0);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200584 }
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000585
586 return false;
587}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000588
Pierre Ossman6c97fa42018-10-05 17:35:51 +0200589void VNCServerST::queryConnection(VNCSConnectionST* client,
Pierre Ossmaneef6c9a2018-10-05 17:11:25 +0200590 const char* userName)
591{
Pierre Ossman6c97fa42018-10-05 17:35:51 +0200592 // - Authentication succeeded - clear from blacklist
593 CharArray name;
594 name.buf = client->getSock()->getPeerAddress();
595 blHosts->clearBlackmark(name.buf);
596
597 // - Prepare the desktop for that the client will start requiring
598 // resources after this
599 startDesktop();
600
601 // - Special case to provide a more useful error message
602 if (rfb::Server::neverShared &&
603 !rfb::Server::disconnectClients &&
604 authClientCount() > 0) {
605 approveConnection(client->getSock(), false,
606 "The server is already in use");
607 return;
608 }
609
610 // - Are we configured to do queries?
611 if (!rfb::Server::queryConnect &&
612 !client->getSock()->requiresQuery()) {
613 approveConnection(client->getSock(), true, NULL);
614 return;
615 }
616
617 // - Does the client have the right to bypass the query?
618 if (client->accessCheck(SConnection::AccessNoQuery))
619 {
620 approveConnection(client->getSock(), true, NULL);
621 return;
622 }
623
624 desktop->queryConnection(client->getSock(), userName);
625}
626
627void VNCServerST::clientReady(VNCSConnectionST* client, bool shared)
628{
629 if (!shared) {
630 if (rfb::Server::disconnectClients &&
631 client->accessCheck(SConnection::AccessNonShared)) {
632 // - Close all the other connected clients
633 slog.debug("non-shared connection - closing clients");
634 closeClients("Non-shared connection requested", client->getSock());
635 } else {
636 // - Refuse this connection if there are existing clients, in addition to
637 // this one
638 if (authClientCount() > 1) {
639 client->close("Server is already in use");
640 return;
641 }
642 }
643 }
Pierre Ossmaneef6c9a2018-10-05 17:11:25 +0200644}
645
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000646// -=- Internal methods
647
648void VNCServerST::startDesktop()
649{
650 if (!desktopStarted) {
651 slog.debug("starting desktop");
652 desktop->start(this);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000653 if (!pb)
654 throw Exception("SDesktop::start() did not set a valid PixelBuffer");
Pierre Ossman6cd61172018-05-07 14:24:56 +0200655 desktopStarted = true;
656 // The tracker might have accumulated changes whilst we were
657 // stopped, so flush those out
658 if (!comparer->is_empty())
659 writeUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000660 }
661}
662
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100663void VNCServerST::stopDesktop()
664{
665 if (desktopStarted) {
666 slog.debug("stopping desktop");
667 desktopStarted = false;
668 desktop->stop();
669 stopFrameClock();
670 }
671}
672
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000673int VNCServerST::authClientCount() {
674 int count = 0;
675 std::list<VNCSConnectionST*>::iterator ci;
676 for (ci = clients.begin(); ci != clients.end(); ci++) {
677 if ((*ci)->authenticated())
678 count++;
679 }
680 return count;
681}
682
683inline bool VNCServerST::needRenderedCursor()
684{
685 std::list<VNCSConnectionST*>::iterator ci;
686 for (ci = clients.begin(); ci != clients.end(); ci++)
687 if ((*ci)->needRenderedCursor()) return true;
688 return false;
689}
690
Pierre Ossman6e49e952016-10-07 15:59:38 +0200691void VNCServerST::startFrameClock()
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000692{
Pierre Ossman6e49e952016-10-07 15:59:38 +0200693 if (frameTimer.isStarted())
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000694 return;
Pierre Ossman559a2e82012-01-23 15:54:11 +0000695 if (blockCounter > 0)
696 return;
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100697 if (!desktopStarted)
698 return;
Pierre Ossman559a2e82012-01-23 15:54:11 +0000699
Pierre Ossman7be73d72017-11-06 13:16:35 +0100700 // The first iteration will be just half a frame as we get a very
701 // unstable update rate if we happen to be perfectly in sync with
702 // the application's update rate
703 frameTimer.start(1000/rfb::Server::frameRate/2);
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000704}
705
Pierre Ossman6e49e952016-10-07 15:59:38 +0200706void VNCServerST::stopFrameClock()
707{
708 frameTimer.stop();
709}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000710
Pierre Ossmana2b80d62018-03-23 09:30:09 +0100711int VNCServerST::msToNextUpdate()
712{
713 // FIXME: If the application is updating slower than frameRate then
714 // we could allow the clients more time here
715
716 if (!frameTimer.isStarted())
717 return 1000/rfb::Server::frameRate/2;
718 else
719 return frameTimer.getRemainingMs();
720}
721
Pierre Ossman6e49e952016-10-07 15:59:38 +0200722// writeUpdate() is called on a regular interval in order to see what
723// updates are pending and propagates them to the update tracker for
724// each client. It uses the ComparingUpdateTracker's compare() method
725// to filter out areas of the screen which haven't actually changed. It
726// also checks the state of the (server-side) rendered cursor, if
727// necessary rendering it again with the correct background.
728
729void VNCServerST::writeUpdate()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000730{
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000731 UpdateInfo ui;
Pierre Ossman6e49e952016-10-07 15:59:38 +0200732 Region toCheck;
733
734 std::list<VNCSConnectionST*>::iterator ci, ci_next;
735
736 assert(blockCounter == 0);
Pierre Ossmanb53c3bf2018-03-22 16:01:44 +0100737 assert(desktopStarted);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200738
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000739 comparer->getUpdateInfo(&ui, pb->getRect());
Pierre Ossman6e49e952016-10-07 15:59:38 +0200740 toCheck = ui.changed.union_(ui.copied);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000741
Pierre Ossman6e49e952016-10-07 15:59:38 +0200742 if (needRenderedCursor()) {
Pierre Ossman6a1a0d02017-02-19 15:48:17 +0100743 Rect clippedCursorRect = Rect(0, 0, cursor->width(), cursor->height())
744 .translate(cursorPos.subtract(cursor->hotspot()))
745 .intersect(pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000746
Pierre Ossman24684e52016-12-05 16:58:19 +0100747 if (!toCheck.intersect(clippedCursorRect).is_empty())
748 renderedCursorInvalid = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000749 }
750
751 pb->grabRegion(toCheck);
752
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000753 if (getComparerState())
754 comparer->enable();
755 else
756 comparer->disable();
757
758 if (comparer->compare())
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000759 comparer->getUpdateInfo(&ui, pb->getRect());
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000760
Pierre Ossman6e49e952016-10-07 15:59:38 +0200761 comparer->clear();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000762
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000763 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
764 ci_next = ci; ci_next++;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000765 (*ci)->add_copied(ui.copied, ui.copy_delta);
766 (*ci)->add_changed(ui.changed);
Pierre Ossman6e49e952016-10-07 15:59:38 +0200767 (*ci)->writeFramebufferUpdateOrClose();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000768 }
Pierre Ossman6e49e952016-10-07 15:59:38 +0200769}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000770
Pierre Ossman6e49e952016-10-07 15:59:38 +0200771// checkUpdate() is called by clients to see if it is safe to read from
772// the framebuffer at this time.
773
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100774Region VNCServerST::getPendingRegion()
Pierre Ossman6e49e952016-10-07 15:59:38 +0200775{
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100776 UpdateInfo ui;
777
Pierre Ossman6e49e952016-10-07 15:59:38 +0200778 // Block clients as the frame buffer cannot be safely accessed
779 if (blockCounter > 0)
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100780 return pb->getRect();
Pierre Ossman6e49e952016-10-07 15:59:38 +0200781
782 // Block client from updating if there are pending updates
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100783 if (comparer->is_empty())
784 return Region();
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000785
Pierre Ossman8efc7b42018-03-23 11:45:51 +0100786 comparer->getUpdateInfo(&ui, pb->getRect());
787
788 return ui.changed.union_(ui.copied);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000789}
790
Pierre Ossman24684e52016-12-05 16:58:19 +0100791const RenderedCursor* VNCServerST::getRenderedCursor()
792{
793 if (renderedCursorInvalid) {
Pierre Ossman7cb4f312017-02-24 13:25:00 +0100794 renderedCursor.update(pb, cursor, cursorPos);
Pierre Ossman24684e52016-12-05 16:58:19 +0100795 renderedCursorInvalid = false;
796 }
797
798 return &renderedCursor;
799}
800
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000801bool VNCServerST::getComparerState()
802{
803 if (rfb::Server::compareFB == 0)
804 return false;
805 if (rfb::Server::compareFB != 2)
806 return true;
807
808 std::list<VNCSConnectionST*>::iterator ci, ci_next;
809 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
810 ci_next = ci; ci_next++;
811 if ((*ci)->getComparerState())
812 return true;
813 }
814 return false;
815}