blob: 838f06c3a02e5baf32cecd2efa04dc38976ea032 [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();
150 }
151 return;
152 }
153 }
154
155 // - If the Socket has no resources, it may have been a closingSocket
156 closingSockets.remove(sock);
157}
158
159void VNCServerST::processSocketEvent(network::Socket* sock)
160{
161 // - Find the appropriate VNCSConnectionST and process the event
162 std::list<VNCSConnectionST*>::iterator ci;
163 for (ci = clients.begin(); ci != clients.end(); ci++) {
164 if ((*ci)->getSock() == sock) {
165 (*ci)->processMessages();
166 return;
167 }
168 }
169 throw rdr::Exception("invalid Socket in VNCServerST");
170}
171
172int VNCServerST::checkTimeouts()
173{
174 int timeout = 0;
175 std::list<VNCSConnectionST*>::iterator ci, ci_next;
176 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
177 ci_next = ci; ci_next++;
178 soonestTimeout(&timeout, (*ci)->checkIdleTimeout());
179 }
180
181 int timeLeft;
Constantin Kaplinsky8499d0c2008-08-21 05:51:29 +0000182 time_t now = time(0);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000183
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000184 // Check MaxDisconnectionTime
185 if (rfb::Server::maxDisconnectionTime && clients.empty()) {
186 if (now < lastDisconnectTime) {
187 // Someone must have set the time backwards.
188 slog.info("Time has gone backwards - resetting lastDisconnectTime");
189 lastDisconnectTime = now;
190 }
191 timeLeft = lastDisconnectTime + rfb::Server::maxDisconnectionTime - now;
192 if (timeLeft < -60) {
193 // Someone must have set the time forwards.
194 slog.info("Time has gone forwards - resetting lastDisconnectTime");
195 lastDisconnectTime = now;
196 timeLeft = rfb::Server::maxDisconnectionTime;
197 }
198 if (timeLeft <= 0) {
199 slog.info("MaxDisconnectionTime reached, exiting");
200 exit(0);
201 }
202 soonestTimeout(&timeout, timeLeft * 1000);
203 }
204
205 // Check MaxConnectionTime
206 if (rfb::Server::maxConnectionTime && lastConnectionTime && !clients.empty()) {
207 if (now < lastConnectionTime) {
208 // Someone must have set the time backwards.
209 slog.info("Time has gone backwards - resetting lastConnectionTime");
210 lastConnectionTime = now;
211 }
212 timeLeft = lastConnectionTime + rfb::Server::maxConnectionTime - now;
213 if (timeLeft < -60) {
214 // Someone must have set the time forwards.
215 slog.info("Time has gone forwards - resetting lastConnectionTime");
216 lastConnectionTime = now;
217 timeLeft = rfb::Server::maxConnectionTime;
218 }
219 if (timeLeft <= 0) {
220 slog.info("MaxConnectionTime reached, exiting");
221 exit(0);
222 }
223 soonestTimeout(&timeout, timeLeft * 1000);
224 }
225
226
227 // Check MaxIdleTime
228 if (rfb::Server::maxIdleTime) {
229 if (now < lastUserInputTime) {
230 // Someone must have set the time backwards.
231 slog.info("Time has gone backwards - resetting lastUserInputTime");
232 lastUserInputTime = now;
233 }
234 timeLeft = lastUserInputTime + rfb::Server::maxIdleTime - now;
235 if (timeLeft < -60) {
236 // Someone must have set the time forwards.
237 slog.info("Time has gone forwards - resetting lastUserInputTime");
238 lastUserInputTime = now;
239 timeLeft = rfb::Server::maxIdleTime;
240 }
241 if (timeLeft <= 0) {
242 slog.info("MaxIdleTime reached, exiting");
243 exit(0);
244 }
245 soonestTimeout(&timeout, timeLeft * 1000);
246 }
247
248 return timeout;
249}
250
251
252// VNCServer methods
253
254void VNCServerST::setPixelBuffer(PixelBuffer* pb_)
255{
256 pb = pb_;
257 delete comparer;
258 comparer = 0;
259
260 if (pb) {
261 comparer = new ComparingUpdateTracker(pb);
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000262 applyVideoRectangle();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000263 cursor.setPF(pb->getPF());
264 renderedCursor.setPF(pb->getPF());
265
266 std::list<VNCSConnectionST*>::iterator ci, ci_next;
267 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
268 ci_next = ci; ci_next++;
269 (*ci)->pixelBufferChange();
270 }
271 } else {
272 if (desktopStarted)
273 throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
274 }
275}
276
277void VNCServerST::setColourMapEntries(int firstColour, int nColours)
278{
279 std::list<VNCSConnectionST*>::iterator ci, ci_next;
280 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
281 ci_next = ci; ci_next++;
282 (*ci)->setColourMapEntriesOrClose(firstColour, nColours);
283 }
284}
285
286void VNCServerST::bell()
287{
288 std::list<VNCSConnectionST*>::iterator ci, ci_next;
289 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
290 ci_next = ci; ci_next++;
291 (*ci)->bell();
292 }
293}
294
295void VNCServerST::serverCutText(const char* str, int len)
296{
297 std::list<VNCSConnectionST*>::iterator ci, ci_next;
298 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
299 ci_next = ci; ci_next++;
300 (*ci)->serverCutText(str, len);
301 }
302}
303
304void VNCServerST::add_changed(const Region& region)
305{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000306 if (comparer != 0) {
307 comparer->add_changed(region);
308 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000309}
310
311void VNCServerST::add_copied(const Region& dest, const Point& delta)
312{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000313 if (comparer != 0) {
314 comparer->add_copied(dest, delta);
315 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000316}
317
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000318void VNCServerST::set_video_area(const Rect &rect)
319{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000320 if (comparer != 0) {
321 comparer->set_video_area(rect);
322 }
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000323}
324
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000325bool VNCServerST::clientsReadyForUpdate()
326{
327 std::list<VNCSConnectionST*>::iterator ci;
328 for (ci = clients.begin(); ci != clients.end(); ci++) {
329 if ((*ci)->readyForUpdate())
330 return true;
331 }
332 return false;
333}
334
335void VNCServerST::tryUpdate()
336{
337 std::list<VNCSConnectionST*>::iterator ci, ci_next;
338 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
339 ci_next = ci; ci_next++;
340 (*ci)->writeFramebufferUpdateOrClose();
341 }
342}
343
344void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
345 void* data, void* mask)
346{
347 cursor.hotspot = newHotspot;
348 cursor.setSize(width, height);
349 memcpy(cursor.data, data, cursor.dataLen());
350 memcpy(cursor.mask.buf, mask, cursor.maskLen());
351
352 cursor.crop();
353
354 renderedCursorInvalid = true;
355
356 std::list<VNCSConnectionST*>::iterator ci, ci_next;
357 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
358 ci_next = ci; ci_next++;
359 (*ci)->renderedCursorChange();
360 (*ci)->setCursorOrClose();
361 }
362}
363
364void VNCServerST::setCursorPos(const Point& pos)
365{
366 if (!cursorPos.equals(pos)) {
367 cursorPos = pos;
368 renderedCursorInvalid = true;
369 std::list<VNCSConnectionST*>::iterator ci;
370 for (ci = clients.begin(); ci != clients.end(); ci++)
371 (*ci)->renderedCursorChange();
372 }
373}
374
375// Other public methods
376
377void VNCServerST::approveConnection(network::Socket* sock, bool accept,
378 const char* reason)
379{
380 std::list<VNCSConnectionST*>::iterator ci;
381 for (ci = clients.begin(); ci != clients.end(); ci++) {
382 if ((*ci)->getSock() == sock) {
383 (*ci)->approveConnectionOrClose(accept, reason);
384 return;
385 }
386 }
387}
388
389void VNCServerST::closeClients(const char* reason, network::Socket* except)
390{
391 std::list<VNCSConnectionST*>::iterator i, next_i;
392 for (i=clients.begin(); i!=clients.end(); i=next_i) {
393 next_i = i; next_i++;
394 if ((*i)->getSock() != except)
395 (*i)->close(reason);
396 }
397}
398
399void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
400{
401 sockets->clear();
402 std::list<VNCSConnectionST*>::iterator ci;
403 for (ci = clients.begin(); ci != clients.end(); ci++) {
404 sockets->push_back((*ci)->getSock());
405 }
406 std::list<network::Socket*>::iterator si;
407 for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
408 sockets->push_back(*si);
409 }
410}
411
412SConnection* VNCServerST::getSConnection(network::Socket* sock) {
413 std::list<VNCSConnectionST*>::iterator ci;
414 for (ci = clients.begin(); ci != clients.end(); ci++) {
415 if ((*ci)->getSock() == sock)
416 return *ci;
417 }
418 return 0;
419}
420
421
422// -=- Internal methods
423
424void VNCServerST::startDesktop()
425{
426 if (!desktopStarted) {
427 slog.debug("starting desktop");
428 desktop->start(this);
429 desktopStarted = true;
430 if (!pb)
431 throw Exception("SDesktop::start() did not set a valid PixelBuffer");
432 }
433}
434
435int VNCServerST::authClientCount() {
436 int count = 0;
437 std::list<VNCSConnectionST*>::iterator ci;
438 for (ci = clients.begin(); ci != clients.end(); ci++) {
439 if ((*ci)->authenticated())
440 count++;
441 }
442 return count;
443}
444
445inline bool VNCServerST::needRenderedCursor()
446{
447 std::list<VNCSConnectionST*>::iterator ci;
448 for (ci = clients.begin(); ci != clients.end(); ci++)
449 if ((*ci)->needRenderedCursor()) return true;
450 return false;
451}
452
453// checkUpdate() is called just before sending an update. It checks to see
454// what updates are pending and propagates them to the update tracker for each
455// client. It uses the ComparingUpdateTracker's compare() method to filter out
456// areas of the screen which haven't actually changed. It also checks the
457// state of the (server-side) rendered cursor, if necessary rendering it again
458// with the correct background.
459
460void VNCServerST::checkUpdate()
461{
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000462 UpdateInfo ui;
463 comparer->getUpdateInfo(&ui, pb->getRect());
464
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000465 bool renderCursor = needRenderedCursor();
466
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000467 if (ui.is_empty() && !(renderCursor && renderedCursorInvalid))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000468 return;
469
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000470 Region toCheck = ui.changed.union_(ui.copied).union_(ui.video_area);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000471
472 if (renderCursor) {
473 Rect clippedCursorRect
474 = cursor.getRect(cursorTL()).intersect(pb->getRect());
475
476 if (!renderedCursorInvalid && (toCheck.intersect(clippedCursorRect)
477 .is_empty())) {
478 renderCursor = false;
479 } else {
480 renderedCursorTL = clippedCursorRect.tl;
481 renderedCursor.setSize(clippedCursorRect.width(),
482 clippedCursorRect.height());
483 toCheck.assign_union(clippedCursorRect);
484 }
485 }
486
487 pb->grabRegion(toCheck);
488
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000489 if (rfb::Server::compareFB) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000490 comparer->compare();
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000491 comparer->getUpdateInfo(&ui, pb->getRect());
492 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000493
494 if (renderCursor) {
495 pb->getImage(renderedCursor.data,
496 renderedCursor.getRect(renderedCursorTL));
497 renderedCursor.maskRect(cursor.getRect(cursorTL()
498 .subtract(renderedCursorTL)),
499 cursor.data, cursor.mask.buf);
500 renderedCursorInvalid = false;
501 }
502
503 std::list<VNCSConnectionST*>::iterator ci, ci_next;
504 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
505 ci_next = ci; ci_next++;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000506 (*ci)->add_copied(ui.copied, ui.copy_delta);
507 (*ci)->add_changed(ui.changed);
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000508 (*ci)->set_video_area(ui.video_area);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000509 }
510
511 comparer->clear();
512}
513
Constantin Kaplinsky6970b2d2008-06-13 18:07:53 +0000514void VNCServerST::checkVideoUpdate()
515{
516 const Rect &videoRect = comparer->getVideoArea();
517 Region videoRegion(videoRect);
518
519 if (!videoRegion.is_empty()) {
520 pb->grabRegion(videoRegion);
521
522 std::list<VNCSConnectionST*>::iterator ci, ci_next;
523 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
524 ci_next = ci; ci_next++;
525 (*ci)->set_video_area(videoRect);
526 }
527 }
528}
529
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000530void VNCServerST::getConnInfo(ListConnInfo * listConn)
531{
532 listConn->Clear();
533 listConn->setDisable(getDisable());
534 if (clients.empty())
535 return;
536 std::list<VNCSConnectionST*>::iterator i;
537 for (i = clients.begin(); i != clients.end(); i++)
538 listConn->addInfo((void*)(*i), (*i)->getSock()->getPeerAddress(),
539 (*i)->getStartTime(), (*i)->getStatus());
540}
541
542void VNCServerST::setConnStatus(ListConnInfo* listConn)
543{
544 setDisable(listConn->getDisable());
545 if (listConn->Empty() || clients.empty()) return;
546 for (listConn->iBegin(); !listConn->iEnd(); listConn->iNext()) {
547 VNCSConnectionST* conn = (VNCSConnectionST*)listConn->iGetConn();
548 std::list<VNCSConnectionST*>::iterator i;
549 for (i = clients.begin(); i != clients.end(); i++) {
550 if ((*i) == conn) {
551 int status = listConn->iGetStatus();
552 if (status == 3) {
553 (*i)->close(0);
554 } else {
555 (*i)->setStatus(status);
556 }
557 break;
558 }
559 }
560 }
561}
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000562
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000563void VNCServerST::enableVideoSelection(bool enable)
564{
565 slog.debug("Enabling video selection");
566 m_videoSelectionEnabled = enable;
567 applyVideoRectangle();
568}
569
570bool VNCServerST::isVideoSelectionEnabled() const
571{
572 return m_videoSelectionEnabled;
573}
574
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000575void VNCServerST::setVideoRectangle(const Rect& r)
576{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000577 m_videoRect = r;
578 applyVideoRectangle();
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000579}
580
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000581void VNCServerST::setDefaultVideoRectangle(const Rect& r)
Constantin Kaplinskyc341ac62008-08-21 03:35:08 +0000582{
583 m_defaultVideoRect = r;
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000584 applyVideoRectangle();
585}
586
587void VNCServerST::applyVideoRectangle()
588{
589 if (pb != 0) {
590 if (isVideoSelectionEnabled() && !m_videoRect.is_empty()) {
591 slog.debug("Applying video selection");
592 set_video_area(m_videoRect);
593 } else {
594 if (!m_defaultVideoRect.is_empty()) {
595 slog.debug("Applying default video area");
596 } else {
597 slog.debug("Applying empty video area");
598 }
599 set_video_area(m_defaultVideoRect);
600 }
Constantin Kaplinsky53bdd3f2008-08-21 04:10:58 +0000601 }
Constantin Kaplinskyc341ac62008-08-21 03:35:08 +0000602}