blob: fc2e931bd6c756d765339c5282d4624ab7cf48f9 [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 *
3 * This is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This software is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
16 * USA.
17 */
18
19// -=- Single-Threaded VNC Server implementation
20
21
22// Note about how sockets get closed:
23//
24// Closing sockets to clients is non-trivial because the code which calls
25// VNCServerST must explicitly know about all the sockets (so that it can block
26// on them appropriately). However, VNCServerST may want to close clients for
27// a number of reasons, and from a variety of entry points. The simplest is
28// when processSocketEvent() is called for a client, and the remote end has
29// closed its socket. A more complex reason is when processSocketEvent() is
30// called for a client which has just sent a ClientInit with the shared flag
31// set to false - in this case we want to close all other clients. Yet another
32// reason for disconnecting clients is when the desktop size has changed as a
33// result of a call to setPixelBuffer().
34//
35// The responsibility for creating and deleting sockets is entirely with the
36// calling code. When VNCServerST wants to close a connection to a client it
37// calls the VNCSConnectionST's close() method which calls shutdown() on the
38// socket. Eventually the calling code will notice that the socket has been
39// shut down and call removeSocket() so that we can delete the
40// VNCSConnectionST. Note that the socket must not be deleted by the calling
41// code until after removeSocket() has been called.
42//
43// One minor complication is that we don't allocate a VNCSConnectionST object
44// for a blacklisted host (since we want to minimise the resources used for
45// dealing with such a connection). In order to properly implement the
46// getSockets function, we must maintain a separate closingSockets list,
47// otherwise blacklisted connections might be "forgotten".
48
49
50#include <rfb/ServerCore.h>
51#include <rfb/VNCServerST.h>
52#include <rfb/VNCSConnectionST.h>
53#include <rfb/ComparingUpdateTracker.h>
54#include <rfb/SSecurityFactoryStandard.h>
55#include <rfb/KeyRemapper.h>
56#include <rfb/util.h>
57
58#include <rdr/types.h>
59
60using namespace rfb;
61
62static LogWriter slog("VNCServerST");
63LogWriter VNCServerST::connectionsLog("Connections");
64static SSecurityFactoryStandard defaultSecurityFactory;
65
66//
67// -=- VNCServerST Implementation
68//
69
70// -=- Constructors/Destructor
71
72VNCServerST::VNCServerST(const char* name_, SDesktop* desktop_,
73 SSecurityFactory* sf)
74 : blHosts(&blacklist), desktop(desktop_), desktopStarted(false), pb(0),
75 m_pFTManager(0), name(strDup(name_)), pointerClient(0), comparer(0),
76 renderedCursorInvalid(false),
77 securityFactory(sf ? sf : &defaultSecurityFactory),
78 queryConnectionHandler(0), keyRemapper(&KeyRemapper::defInstance),
79 useEconomicTranslate(false),
Constantin Kaplinsky82328312008-04-24 08:44:24 +000080 lastConnectionTime(0), disableclients(false),
81 m_videoSelectionEnabled(false)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000082{
83 lastUserInputTime = lastDisconnectTime = time(0);
84 slog.debug("creating single-threaded server %s", name.buf);
85}
86
87VNCServerST::~VNCServerST()
88{
89 slog.debug("shutting down server %s", name.buf);
90
91 // Close any active clients, with appropriate logging & cleanup
92 closeClients("Server shutdown");
93
94 // Delete all the clients, and their sockets, and any closing sockets
95 // NB: Deleting a client implicitly removes it from the clients list
96 while (!clients.empty()) {
97 delete clients.front();
98 }
99
100 // Stop the desktop object if active, *only* after deleting all clients!
101 if (desktopStarted) {
102 desktopStarted = false;
103 desktop->stop();
104 }
105
106 delete comparer;
107}
108
109
110// SocketServer methods
111
112void VNCServerST::addSocket(network::Socket* sock, bool outgoing)
113{
114 // - Check the connection isn't black-marked
115 // *** do this in getSecurity instead?
116 CharArray address(sock->getPeerAddress());
117 if (blHosts->isBlackmarked(address.buf)) {
118 connectionsLog.error("blacklisted: %s", address.buf);
119 try {
120 SConnection::writeConnFailedFromScratch("Too many security failures",
121 &sock->outStream());
122 } catch (rdr::Exception&) {
123 }
124 sock->shutdown();
125 closingSockets.push_back(sock);
126 return;
127 }
128
129 if (clients.empty()) {
130 lastConnectionTime = time(0);
131 }
132
133 VNCSConnectionST* client = new VNCSConnectionST(this, sock, outgoing);
134 client->init();
135}
136
137void VNCServerST::removeSocket(network::Socket* sock) {
138 // - If the socket has resources allocated to it, delete them
139 std::list<VNCSConnectionST*>::iterator ci;
140 for (ci = clients.begin(); ci != clients.end(); ci++) {
141 if ((*ci)->getSock() == sock) {
142 // - Delete the per-Socket resources
143 delete *ci;
144
145 // - Check that the desktop object is still required
146 if (authClientCount() == 0 && desktopStarted) {
147 slog.debug("no authenticated clients - stopping desktop");
148 desktopStarted = false;
149 desktop->stop();
Constantin Kaplinsky433eb1b2008-09-05 05:14:03 +0000150 setVideoRectangle(Rect(0, 0, 0, 0));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000151 }
152 return;
153 }
154 }
155
156 // - If the Socket has no resources, it may have been a closingSocket
157 closingSockets.remove(sock);
158}
159
160void VNCServerST::processSocketEvent(network::Socket* sock)
161{
162 // - Find the appropriate VNCSConnectionST and process the event
163 std::list<VNCSConnectionST*>::iterator ci;
164 for (ci = clients.begin(); ci != clients.end(); ci++) {
165 if ((*ci)->getSock() == sock) {
166 (*ci)->processMessages();
167 return;
168 }
169 }
170 throw rdr::Exception("invalid Socket in VNCServerST");
171}
172
173int VNCServerST::checkTimeouts()
174{
175 int timeout = 0;
176 std::list<VNCSConnectionST*>::iterator ci, ci_next;
177 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
178 ci_next = ci; ci_next++;
179 soonestTimeout(&timeout, (*ci)->checkIdleTimeout());
180 }
181
182 int timeLeft;
Constantin Kaplinsky8499d0c2008-08-21 05:51:29 +0000183 time_t now = time(0);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000184
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000185 // Check MaxDisconnectionTime
186 if (rfb::Server::maxDisconnectionTime && clients.empty()) {
187 if (now < lastDisconnectTime) {
188 // Someone must have set the time backwards.
189 slog.info("Time has gone backwards - resetting lastDisconnectTime");
190 lastDisconnectTime = now;
191 }
192 timeLeft = lastDisconnectTime + rfb::Server::maxDisconnectionTime - now;
193 if (timeLeft < -60) {
194 // Someone must have set the time forwards.
195 slog.info("Time has gone forwards - resetting lastDisconnectTime");
196 lastDisconnectTime = now;
197 timeLeft = rfb::Server::maxDisconnectionTime;
198 }
199 if (timeLeft <= 0) {
200 slog.info("MaxDisconnectionTime reached, exiting");
201 exit(0);
202 }
203 soonestTimeout(&timeout, timeLeft * 1000);
204 }
205
206 // Check MaxConnectionTime
207 if (rfb::Server::maxConnectionTime && lastConnectionTime && !clients.empty()) {
208 if (now < lastConnectionTime) {
209 // Someone must have set the time backwards.
210 slog.info("Time has gone backwards - resetting lastConnectionTime");
211 lastConnectionTime = now;
212 }
213 timeLeft = lastConnectionTime + rfb::Server::maxConnectionTime - now;
214 if (timeLeft < -60) {
215 // Someone must have set the time forwards.
216 slog.info("Time has gone forwards - resetting lastConnectionTime");
217 lastConnectionTime = now;
218 timeLeft = rfb::Server::maxConnectionTime;
219 }
220 if (timeLeft <= 0) {
221 slog.info("MaxConnectionTime reached, exiting");
222 exit(0);
223 }
224 soonestTimeout(&timeout, timeLeft * 1000);
225 }
226
227
228 // Check MaxIdleTime
229 if (rfb::Server::maxIdleTime) {
230 if (now < lastUserInputTime) {
231 // Someone must have set the time backwards.
232 slog.info("Time has gone backwards - resetting lastUserInputTime");
233 lastUserInputTime = now;
234 }
235 timeLeft = lastUserInputTime + rfb::Server::maxIdleTime - now;
236 if (timeLeft < -60) {
237 // Someone must have set the time forwards.
238 slog.info("Time has gone forwards - resetting lastUserInputTime");
239 lastUserInputTime = now;
240 timeLeft = rfb::Server::maxIdleTime;
241 }
242 if (timeLeft <= 0) {
243 slog.info("MaxIdleTime reached, exiting");
244 exit(0);
245 }
246 soonestTimeout(&timeout, timeLeft * 1000);
247 }
248
249 return timeout;
250}
251
252
253// VNCServer methods
254
255void VNCServerST::setPixelBuffer(PixelBuffer* pb_)
256{
257 pb = pb_;
258 delete comparer;
259 comparer = 0;
260
261 if (pb) {
262 comparer = new ComparingUpdateTracker(pb);
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000263 applyVideoRectangle();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000264 cursor.setPF(pb->getPF());
265 renderedCursor.setPF(pb->getPF());
266
267 std::list<VNCSConnectionST*>::iterator ci, ci_next;
268 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
269 ci_next = ci; ci_next++;
270 (*ci)->pixelBufferChange();
271 }
272 } else {
273 if (desktopStarted)
274 throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
275 }
276}
277
278void VNCServerST::setColourMapEntries(int firstColour, int nColours)
279{
280 std::list<VNCSConnectionST*>::iterator ci, ci_next;
281 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
282 ci_next = ci; ci_next++;
283 (*ci)->setColourMapEntriesOrClose(firstColour, nColours);
284 }
285}
286
287void VNCServerST::bell()
288{
289 std::list<VNCSConnectionST*>::iterator ci, ci_next;
290 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
291 ci_next = ci; ci_next++;
292 (*ci)->bell();
293 }
294}
295
296void VNCServerST::serverCutText(const char* str, int len)
297{
298 std::list<VNCSConnectionST*>::iterator ci, ci_next;
299 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
300 ci_next = ci; ci_next++;
301 (*ci)->serverCutText(str, len);
302 }
303}
304
305void VNCServerST::add_changed(const Region& region)
306{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000307 if (comparer != 0) {
308 comparer->add_changed(region);
309 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000310}
311
312void VNCServerST::add_copied(const Region& dest, const Point& delta)
313{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000314 if (comparer != 0) {
315 comparer->add_copied(dest, delta);
316 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000317}
318
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000319void VNCServerST::set_video_area(const Rect &rect)
320{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000321 if (comparer != 0) {
322 comparer->set_video_area(rect);
323 }
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000324}
325
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000326bool VNCServerST::clientsReadyForUpdate()
327{
328 std::list<VNCSConnectionST*>::iterator ci;
329 for (ci = clients.begin(); ci != clients.end(); ci++) {
330 if ((*ci)->readyForUpdate())
331 return true;
332 }
333 return false;
334}
335
336void VNCServerST::tryUpdate()
337{
338 std::list<VNCSConnectionST*>::iterator ci, ci_next;
339 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
340 ci_next = ci; ci_next++;
341 (*ci)->writeFramebufferUpdateOrClose();
342 }
343}
344
345void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
346 void* data, void* mask)
347{
348 cursor.hotspot = newHotspot;
349 cursor.setSize(width, height);
350 memcpy(cursor.data, data, cursor.dataLen());
351 memcpy(cursor.mask.buf, mask, cursor.maskLen());
352
353 cursor.crop();
354
355 renderedCursorInvalid = true;
356
357 std::list<VNCSConnectionST*>::iterator ci, ci_next;
358 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
359 ci_next = ci; ci_next++;
360 (*ci)->renderedCursorChange();
361 (*ci)->setCursorOrClose();
362 }
363}
364
365void VNCServerST::setCursorPos(const Point& pos)
366{
367 if (!cursorPos.equals(pos)) {
368 cursorPos = pos;
369 renderedCursorInvalid = true;
370 std::list<VNCSConnectionST*>::iterator ci;
371 for (ci = clients.begin(); ci != clients.end(); ci++)
372 (*ci)->renderedCursorChange();
373 }
374}
375
376// Other public methods
377
378void VNCServerST::approveConnection(network::Socket* sock, bool accept,
379 const char* reason)
380{
381 std::list<VNCSConnectionST*>::iterator ci;
382 for (ci = clients.begin(); ci != clients.end(); ci++) {
383 if ((*ci)->getSock() == sock) {
384 (*ci)->approveConnectionOrClose(accept, reason);
385 return;
386 }
387 }
388}
389
390void VNCServerST::closeClients(const char* reason, network::Socket* except)
391{
392 std::list<VNCSConnectionST*>::iterator i, next_i;
393 for (i=clients.begin(); i!=clients.end(); i=next_i) {
394 next_i = i; next_i++;
395 if ((*i)->getSock() != except)
396 (*i)->close(reason);
397 }
398}
399
400void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
401{
402 sockets->clear();
403 std::list<VNCSConnectionST*>::iterator ci;
404 for (ci = clients.begin(); ci != clients.end(); ci++) {
405 sockets->push_back((*ci)->getSock());
406 }
407 std::list<network::Socket*>::iterator si;
408 for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
409 sockets->push_back(*si);
410 }
411}
412
413SConnection* VNCServerST::getSConnection(network::Socket* sock) {
414 std::list<VNCSConnectionST*>::iterator ci;
415 for (ci = clients.begin(); ci != clients.end(); ci++) {
416 if ((*ci)->getSock() == sock)
417 return *ci;
418 }
419 return 0;
420}
421
422
423// -=- Internal methods
424
425void VNCServerST::startDesktop()
426{
427 if (!desktopStarted) {
428 slog.debug("starting desktop");
429 desktop->start(this);
430 desktopStarted = true;
431 if (!pb)
432 throw Exception("SDesktop::start() did not set a valid PixelBuffer");
433 }
434}
435
436int VNCServerST::authClientCount() {
437 int count = 0;
438 std::list<VNCSConnectionST*>::iterator ci;
439 for (ci = clients.begin(); ci != clients.end(); ci++) {
440 if ((*ci)->authenticated())
441 count++;
442 }
443 return count;
444}
445
446inline bool VNCServerST::needRenderedCursor()
447{
448 std::list<VNCSConnectionST*>::iterator ci;
449 for (ci = clients.begin(); ci != clients.end(); ci++)
450 if ((*ci)->needRenderedCursor()) return true;
451 return false;
452}
453
454// checkUpdate() is called just before sending an update. It checks to see
455// what updates are pending and propagates them to the update tracker for each
456// client. It uses the ComparingUpdateTracker's compare() method to filter out
457// areas of the screen which haven't actually changed. It also checks the
458// state of the (server-side) rendered cursor, if necessary rendering it again
459// with the correct background.
460
461void VNCServerST::checkUpdate()
462{
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000463 UpdateInfo ui;
464 comparer->getUpdateInfo(&ui, pb->getRect());
465
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000466 bool renderCursor = needRenderedCursor();
467
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000468 if (ui.is_empty() && !(renderCursor && renderedCursorInvalid))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000469 return;
470
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000471 Region toCheck = ui.changed.union_(ui.copied).union_(ui.video_area);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000472
473 if (renderCursor) {
474 Rect clippedCursorRect
475 = cursor.getRect(cursorTL()).intersect(pb->getRect());
476
477 if (!renderedCursorInvalid && (toCheck.intersect(clippedCursorRect)
478 .is_empty())) {
479 renderCursor = false;
480 } else {
481 renderedCursorTL = clippedCursorRect.tl;
482 renderedCursor.setSize(clippedCursorRect.width(),
483 clippedCursorRect.height());
484 toCheck.assign_union(clippedCursorRect);
485 }
486 }
487
488 pb->grabRegion(toCheck);
489
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000490 if (rfb::Server::compareFB) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000491 comparer->compare();
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000492 comparer->getUpdateInfo(&ui, pb->getRect());
493 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000494
495 if (renderCursor) {
496 pb->getImage(renderedCursor.data,
497 renderedCursor.getRect(renderedCursorTL));
498 renderedCursor.maskRect(cursor.getRect(cursorTL()
499 .subtract(renderedCursorTL)),
500 cursor.data, cursor.mask.buf);
501 renderedCursorInvalid = false;
502 }
503
504 std::list<VNCSConnectionST*>::iterator ci, ci_next;
505 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
506 ci_next = ci; ci_next++;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000507 (*ci)->add_copied(ui.copied, ui.copy_delta);
508 (*ci)->add_changed(ui.changed);
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000509 (*ci)->set_video_area(ui.video_area);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000510 }
511
512 comparer->clear();
513}
514
Constantin Kaplinsky6970b2d2008-06-13 18:07:53 +0000515void VNCServerST::checkVideoUpdate()
516{
517 const Rect &videoRect = comparer->getVideoArea();
518 Region videoRegion(videoRect);
519
520 if (!videoRegion.is_empty()) {
521 pb->grabRegion(videoRegion);
522
523 std::list<VNCSConnectionST*>::iterator ci, ci_next;
524 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
525 ci_next = ci; ci_next++;
526 (*ci)->set_video_area(videoRect);
527 }
528 }
529}
530
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000531void VNCServerST::getConnInfo(ListConnInfo * listConn)
532{
533 listConn->Clear();
534 listConn->setDisable(getDisable());
535 if (clients.empty())
536 return;
537 std::list<VNCSConnectionST*>::iterator i;
538 for (i = clients.begin(); i != clients.end(); i++)
539 listConn->addInfo((void*)(*i), (*i)->getSock()->getPeerAddress(),
540 (*i)->getStartTime(), (*i)->getStatus());
541}
542
543void VNCServerST::setConnStatus(ListConnInfo* listConn)
544{
545 setDisable(listConn->getDisable());
546 if (listConn->Empty() || clients.empty()) return;
547 for (listConn->iBegin(); !listConn->iEnd(); listConn->iNext()) {
548 VNCSConnectionST* conn = (VNCSConnectionST*)listConn->iGetConn();
549 std::list<VNCSConnectionST*>::iterator i;
550 for (i = clients.begin(); i != clients.end(); i++) {
551 if ((*i) == conn) {
552 int status = listConn->iGetStatus();
553 if (status == 3) {
554 (*i)->close(0);
555 } else {
556 (*i)->setStatus(status);
557 }
558 break;
559 }
560 }
561 }
562}
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000563
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000564void VNCServerST::enableVideoSelection(bool enable)
565{
566 slog.debug("Enabling video selection");
567 m_videoSelectionEnabled = enable;
568 applyVideoRectangle();
569}
570
571bool VNCServerST::isVideoSelectionEnabled() const
572{
573 return m_videoSelectionEnabled;
574}
575
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000576void VNCServerST::setVideoRectangle(const Rect& r)
577{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000578 m_videoRect = r;
579 applyVideoRectangle();
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000580}
581
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000582void VNCServerST::setDefaultVideoRectangle(const Rect& r)
Constantin Kaplinskyc341ac62008-08-21 03:35:08 +0000583{
584 m_defaultVideoRect = r;
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000585 applyVideoRectangle();
586}
587
588void VNCServerST::applyVideoRectangle()
589{
590 if (pb != 0) {
591 if (isVideoSelectionEnabled() && !m_videoRect.is_empty()) {
592 slog.debug("Applying video selection");
593 set_video_area(m_videoRect);
594 } else {
595 if (!m_defaultVideoRect.is_empty()) {
596 slog.debug("Applying default video area");
597 } else {
598 slog.debug("Applying empty video area");
599 }
600 set_video_area(m_defaultVideoRect);
601 }
Constantin Kaplinsky53bdd3f2008-08-21 04:10:58 +0000602 }
Constantin Kaplinskyc341ac62008-08-21 03:35:08 +0000603}