blob: 0577d0563ec15d15cdc19ce34fe34fcc8a103aaf [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);
262 cursor.setPF(pb->getPF());
263 renderedCursor.setPF(pb->getPF());
264
265 std::list<VNCSConnectionST*>::iterator ci, ci_next;
266 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
267 ci_next = ci; ci_next++;
268 (*ci)->pixelBufferChange();
269 }
270 } else {
271 if (desktopStarted)
272 throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
273 }
274}
275
276void VNCServerST::setColourMapEntries(int firstColour, int nColours)
277{
278 std::list<VNCSConnectionST*>::iterator ci, ci_next;
279 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
280 ci_next = ci; ci_next++;
281 (*ci)->setColourMapEntriesOrClose(firstColour, nColours);
282 }
283}
284
285void VNCServerST::bell()
286{
287 std::list<VNCSConnectionST*>::iterator ci, ci_next;
288 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
289 ci_next = ci; ci_next++;
290 (*ci)->bell();
291 }
292}
293
294void VNCServerST::serverCutText(const char* str, int len)
295{
296 std::list<VNCSConnectionST*>::iterator ci, ci_next;
297 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
298 ci_next = ci; ci_next++;
299 (*ci)->serverCutText(str, len);
300 }
301}
302
303void VNCServerST::add_changed(const Region& region)
304{
305 comparer->add_changed(region);
306}
307
308void VNCServerST::add_copied(const Region& dest, const Point& delta)
309{
310 comparer->add_copied(dest, delta);
311}
312
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000313void VNCServerST::set_video_area(const Rect &rect)
314{
315 comparer->set_video_area(rect);
316}
317
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000318bool VNCServerST::clientsReadyForUpdate()
319{
320 std::list<VNCSConnectionST*>::iterator ci;
321 for (ci = clients.begin(); ci != clients.end(); ci++) {
322 if ((*ci)->readyForUpdate())
323 return true;
324 }
325 return false;
326}
327
328void VNCServerST::tryUpdate()
329{
330 std::list<VNCSConnectionST*>::iterator ci, ci_next;
331 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
332 ci_next = ci; ci_next++;
333 (*ci)->writeFramebufferUpdateOrClose();
334 }
335}
336
337void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
338 void* data, void* mask)
339{
340 cursor.hotspot = newHotspot;
341 cursor.setSize(width, height);
342 memcpy(cursor.data, data, cursor.dataLen());
343 memcpy(cursor.mask.buf, mask, cursor.maskLen());
344
345 cursor.crop();
346
347 renderedCursorInvalid = true;
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++;
352 (*ci)->renderedCursorChange();
353 (*ci)->setCursorOrClose();
354 }
355}
356
357void VNCServerST::setCursorPos(const Point& pos)
358{
359 if (!cursorPos.equals(pos)) {
360 cursorPos = pos;
361 renderedCursorInvalid = true;
362 std::list<VNCSConnectionST*>::iterator ci;
363 for (ci = clients.begin(); ci != clients.end(); ci++)
364 (*ci)->renderedCursorChange();
365 }
366}
367
368// Other public methods
369
370void VNCServerST::approveConnection(network::Socket* sock, bool accept,
371 const char* reason)
372{
373 std::list<VNCSConnectionST*>::iterator ci;
374 for (ci = clients.begin(); ci != clients.end(); ci++) {
375 if ((*ci)->getSock() == sock) {
376 (*ci)->approveConnectionOrClose(accept, reason);
377 return;
378 }
379 }
380}
381
382void VNCServerST::closeClients(const char* reason, network::Socket* except)
383{
384 std::list<VNCSConnectionST*>::iterator i, next_i;
385 for (i=clients.begin(); i!=clients.end(); i=next_i) {
386 next_i = i; next_i++;
387 if ((*i)->getSock() != except)
388 (*i)->close(reason);
389 }
390}
391
392void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
393{
394 sockets->clear();
395 std::list<VNCSConnectionST*>::iterator ci;
396 for (ci = clients.begin(); ci != clients.end(); ci++) {
397 sockets->push_back((*ci)->getSock());
398 }
399 std::list<network::Socket*>::iterator si;
400 for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
401 sockets->push_back(*si);
402 }
403}
404
405SConnection* VNCServerST::getSConnection(network::Socket* sock) {
406 std::list<VNCSConnectionST*>::iterator ci;
407 for (ci = clients.begin(); ci != clients.end(); ci++) {
408 if ((*ci)->getSock() == sock)
409 return *ci;
410 }
411 return 0;
412}
413
414
415// -=- Internal methods
416
417void VNCServerST::startDesktop()
418{
419 if (!desktopStarted) {
420 slog.debug("starting desktop");
421 desktop->start(this);
422 desktopStarted = true;
423 if (!pb)
424 throw Exception("SDesktop::start() did not set a valid PixelBuffer");
425 }
426}
427
428int VNCServerST::authClientCount() {
429 int count = 0;
430 std::list<VNCSConnectionST*>::iterator ci;
431 for (ci = clients.begin(); ci != clients.end(); ci++) {
432 if ((*ci)->authenticated())
433 count++;
434 }
435 return count;
436}
437
438inline bool VNCServerST::needRenderedCursor()
439{
440 std::list<VNCSConnectionST*>::iterator ci;
441 for (ci = clients.begin(); ci != clients.end(); ci++)
442 if ((*ci)->needRenderedCursor()) return true;
443 return false;
444}
445
446// checkUpdate() is called just before sending an update. It checks to see
447// what updates are pending and propagates them to the update tracker for each
448// client. It uses the ComparingUpdateTracker's compare() method to filter out
449// areas of the screen which haven't actually changed. It also checks the
450// state of the (server-side) rendered cursor, if necessary rendering it again
451// with the correct background.
452
453void VNCServerST::checkUpdate()
454{
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000455 UpdateInfo ui;
456 comparer->getUpdateInfo(&ui, pb->getRect());
457
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000458 bool renderCursor = needRenderedCursor();
459
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000460 if (ui.is_empty() && !(renderCursor && renderedCursorInvalid))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000461 return;
462
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000463 Region toCheck = ui.changed.union_(ui.copied).union_(ui.video_area);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000464
465 if (renderCursor) {
466 Rect clippedCursorRect
467 = cursor.getRect(cursorTL()).intersect(pb->getRect());
468
469 if (!renderedCursorInvalid && (toCheck.intersect(clippedCursorRect)
470 .is_empty())) {
471 renderCursor = false;
472 } else {
473 renderedCursorTL = clippedCursorRect.tl;
474 renderedCursor.setSize(clippedCursorRect.width(),
475 clippedCursorRect.height());
476 toCheck.assign_union(clippedCursorRect);
477 }
478 }
479
480 pb->grabRegion(toCheck);
481
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000482 if (rfb::Server::compareFB) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000483 comparer->compare();
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000484 comparer->getUpdateInfo(&ui, pb->getRect());
485 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000486
487 if (renderCursor) {
488 pb->getImage(renderedCursor.data,
489 renderedCursor.getRect(renderedCursorTL));
490 renderedCursor.maskRect(cursor.getRect(cursorTL()
491 .subtract(renderedCursorTL)),
492 cursor.data, cursor.mask.buf);
493 renderedCursorInvalid = false;
494 }
495
496 std::list<VNCSConnectionST*>::iterator ci, ci_next;
497 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
498 ci_next = ci; ci_next++;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000499 (*ci)->add_copied(ui.copied, ui.copy_delta);
500 (*ci)->add_changed(ui.changed);
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000501 (*ci)->set_video_area(ui.video_area);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000502 }
503
504 comparer->clear();
505}
506
Constantin Kaplinsky6970b2d2008-06-13 18:07:53 +0000507void VNCServerST::checkVideoUpdate()
508{
509 const Rect &videoRect = comparer->getVideoArea();
510 Region videoRegion(videoRect);
511
512 if (!videoRegion.is_empty()) {
513 pb->grabRegion(videoRegion);
514
515 std::list<VNCSConnectionST*>::iterator ci, ci_next;
516 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
517 ci_next = ci; ci_next++;
518 (*ci)->set_video_area(videoRect);
519 }
520 }
521}
522
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000523void VNCServerST::getConnInfo(ListConnInfo * listConn)
524{
525 listConn->Clear();
526 listConn->setDisable(getDisable());
527 if (clients.empty())
528 return;
529 std::list<VNCSConnectionST*>::iterator i;
530 for (i = clients.begin(); i != clients.end(); i++)
531 listConn->addInfo((void*)(*i), (*i)->getSock()->getPeerAddress(),
532 (*i)->getStartTime(), (*i)->getStatus());
533}
534
535void VNCServerST::setConnStatus(ListConnInfo* listConn)
536{
537 setDisable(listConn->getDisable());
538 if (listConn->Empty() || clients.empty()) return;
539 for (listConn->iBegin(); !listConn->iEnd(); listConn->iNext()) {
540 VNCSConnectionST* conn = (VNCSConnectionST*)listConn->iGetConn();
541 std::list<VNCSConnectionST*>::iterator i;
542 for (i = clients.begin(); i != clients.end(); i++) {
543 if ((*i) == conn) {
544 int status = listConn->iGetStatus();
545 if (status == 3) {
546 (*i)->close(0);
547 } else {
548 (*i)->setStatus(status);
549 }
550 break;
551 }
552 }
553 }
554}
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000555
556void VNCServerST::setVideoRectangle(const Rect& r)
557{
558 if (isVideoSelectionEnabled()) {
559 // FIXME: Duplication between m_videoRect and comparer->video_area.
560 m_videoRect = r;
561 set_video_area(m_videoRect);
562 }
563}
564
565void VNCServerST::unsetVideoRectangle()
566{
567 if (isVideoSelectionEnabled()) {
568 // FIXME: Duplication between m_videoRect and comparer->video_area.
569 m_videoRect.clear();
Constantin Kaplinsky53bdd3f2008-08-21 04:10:58 +0000570 set_video_area(m_defaultVideoRect);
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000571 }
572}
573
Constantin Kaplinskyc341ac62008-08-21 03:35:08 +0000574void VNCServerST::setDefaultVideoRect(const Rect& r)
575{
576 m_defaultVideoRect = r;
Constantin Kaplinsky53bdd3f2008-08-21 04:10:58 +0000577 if (m_videoRect.is_empty()) {
578 set_video_area(m_defaultVideoRect);
579 }
Constantin Kaplinskyc341ac62008-08-21 03:35:08 +0000580}