blob: e9544780e74c40e4b64e3195e7872324cf4d7ada [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;
182 time_t now;
183
184 // Optimization: Only call time() if using any maxTime.
185 if (rfb::Server::maxDisconnectionTime || rfb::Server::maxConnectionTime || rfb::Server::maxIdleTime) {
186 now = time(0);
187 }
188
189 // Check MaxDisconnectionTime
190 if (rfb::Server::maxDisconnectionTime && clients.empty()) {
191 if (now < lastDisconnectTime) {
192 // Someone must have set the time backwards.
193 slog.info("Time has gone backwards - resetting lastDisconnectTime");
194 lastDisconnectTime = now;
195 }
196 timeLeft = lastDisconnectTime + rfb::Server::maxDisconnectionTime - now;
197 if (timeLeft < -60) {
198 // Someone must have set the time forwards.
199 slog.info("Time has gone forwards - resetting lastDisconnectTime");
200 lastDisconnectTime = now;
201 timeLeft = rfb::Server::maxDisconnectionTime;
202 }
203 if (timeLeft <= 0) {
204 slog.info("MaxDisconnectionTime reached, exiting");
205 exit(0);
206 }
207 soonestTimeout(&timeout, timeLeft * 1000);
208 }
209
210 // Check MaxConnectionTime
211 if (rfb::Server::maxConnectionTime && lastConnectionTime && !clients.empty()) {
212 if (now < lastConnectionTime) {
213 // Someone must have set the time backwards.
214 slog.info("Time has gone backwards - resetting lastConnectionTime");
215 lastConnectionTime = now;
216 }
217 timeLeft = lastConnectionTime + rfb::Server::maxConnectionTime - now;
218 if (timeLeft < -60) {
219 // Someone must have set the time forwards.
220 slog.info("Time has gone forwards - resetting lastConnectionTime");
221 lastConnectionTime = now;
222 timeLeft = rfb::Server::maxConnectionTime;
223 }
224 if (timeLeft <= 0) {
225 slog.info("MaxConnectionTime reached, exiting");
226 exit(0);
227 }
228 soonestTimeout(&timeout, timeLeft * 1000);
229 }
230
231
232 // Check MaxIdleTime
233 if (rfb::Server::maxIdleTime) {
234 if (now < lastUserInputTime) {
235 // Someone must have set the time backwards.
236 slog.info("Time has gone backwards - resetting lastUserInputTime");
237 lastUserInputTime = now;
238 }
239 timeLeft = lastUserInputTime + rfb::Server::maxIdleTime - now;
240 if (timeLeft < -60) {
241 // Someone must have set the time forwards.
242 slog.info("Time has gone forwards - resetting lastUserInputTime");
243 lastUserInputTime = now;
244 timeLeft = rfb::Server::maxIdleTime;
245 }
246 if (timeLeft <= 0) {
247 slog.info("MaxIdleTime reached, exiting");
248 exit(0);
249 }
250 soonestTimeout(&timeout, timeLeft * 1000);
251 }
252
253 return timeout;
254}
255
256
257// VNCServer methods
258
259void VNCServerST::setPixelBuffer(PixelBuffer* pb_)
260{
261 pb = pb_;
262 delete comparer;
263 comparer = 0;
264
265 if (pb) {
266 comparer = new ComparingUpdateTracker(pb);
267 cursor.setPF(pb->getPF());
268 renderedCursor.setPF(pb->getPF());
269
270 std::list<VNCSConnectionST*>::iterator ci, ci_next;
271 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
272 ci_next = ci; ci_next++;
273 (*ci)->pixelBufferChange();
274 }
275 } else {
276 if (desktopStarted)
277 throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
278 }
279}
280
281void VNCServerST::setColourMapEntries(int firstColour, int nColours)
282{
283 std::list<VNCSConnectionST*>::iterator ci, ci_next;
284 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
285 ci_next = ci; ci_next++;
286 (*ci)->setColourMapEntriesOrClose(firstColour, nColours);
287 }
288}
289
290void VNCServerST::bell()
291{
292 std::list<VNCSConnectionST*>::iterator ci, ci_next;
293 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
294 ci_next = ci; ci_next++;
295 (*ci)->bell();
296 }
297}
298
299void VNCServerST::serverCutText(const char* str, int len)
300{
301 std::list<VNCSConnectionST*>::iterator ci, ci_next;
302 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
303 ci_next = ci; ci_next++;
304 (*ci)->serverCutText(str, len);
305 }
306}
307
308void VNCServerST::add_changed(const Region& region)
309{
310 comparer->add_changed(region);
311}
312
313void VNCServerST::add_copied(const Region& dest, const Point& delta)
314{
315 comparer->add_copied(dest, delta);
316}
317
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000318void VNCServerST::set_video_area(const Rect &rect)
319{
320 comparer->set_video_area(rect);
321}
322
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000323bool VNCServerST::clientsReadyForUpdate()
324{
325 std::list<VNCSConnectionST*>::iterator ci;
326 for (ci = clients.begin(); ci != clients.end(); ci++) {
327 if ((*ci)->readyForUpdate())
328 return true;
329 }
330 return false;
331}
332
333void VNCServerST::tryUpdate()
334{
335 std::list<VNCSConnectionST*>::iterator ci, ci_next;
336 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
337 ci_next = ci; ci_next++;
338 (*ci)->writeFramebufferUpdateOrClose();
339 }
340}
341
342void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
343 void* data, void* mask)
344{
345 cursor.hotspot = newHotspot;
346 cursor.setSize(width, height);
347 memcpy(cursor.data, data, cursor.dataLen());
348 memcpy(cursor.mask.buf, mask, cursor.maskLen());
349
350 cursor.crop();
351
352 renderedCursorInvalid = true;
353
354 std::list<VNCSConnectionST*>::iterator ci, ci_next;
355 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
356 ci_next = ci; ci_next++;
357 (*ci)->renderedCursorChange();
358 (*ci)->setCursorOrClose();
359 }
360}
361
362void VNCServerST::setCursorPos(const Point& pos)
363{
364 if (!cursorPos.equals(pos)) {
365 cursorPos = pos;
366 renderedCursorInvalid = true;
367 std::list<VNCSConnectionST*>::iterator ci;
368 for (ci = clients.begin(); ci != clients.end(); ci++)
369 (*ci)->renderedCursorChange();
370 }
371}
372
373// Other public methods
374
375void VNCServerST::approveConnection(network::Socket* sock, bool accept,
376 const char* reason)
377{
378 std::list<VNCSConnectionST*>::iterator ci;
379 for (ci = clients.begin(); ci != clients.end(); ci++) {
380 if ((*ci)->getSock() == sock) {
381 (*ci)->approveConnectionOrClose(accept, reason);
382 return;
383 }
384 }
385}
386
387void VNCServerST::closeClients(const char* reason, network::Socket* except)
388{
389 std::list<VNCSConnectionST*>::iterator i, next_i;
390 for (i=clients.begin(); i!=clients.end(); i=next_i) {
391 next_i = i; next_i++;
392 if ((*i)->getSock() != except)
393 (*i)->close(reason);
394 }
395}
396
397void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
398{
399 sockets->clear();
400 std::list<VNCSConnectionST*>::iterator ci;
401 for (ci = clients.begin(); ci != clients.end(); ci++) {
402 sockets->push_back((*ci)->getSock());
403 }
404 std::list<network::Socket*>::iterator si;
405 for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
406 sockets->push_back(*si);
407 }
408}
409
410SConnection* VNCServerST::getSConnection(network::Socket* sock) {
411 std::list<VNCSConnectionST*>::iterator ci;
412 for (ci = clients.begin(); ci != clients.end(); ci++) {
413 if ((*ci)->getSock() == sock)
414 return *ci;
415 }
416 return 0;
417}
418
419
420// -=- Internal methods
421
422void VNCServerST::startDesktop()
423{
424 if (!desktopStarted) {
425 slog.debug("starting desktop");
426 desktop->start(this);
427 desktopStarted = true;
428 if (!pb)
429 throw Exception("SDesktop::start() did not set a valid PixelBuffer");
430 }
431}
432
433int VNCServerST::authClientCount() {
434 int count = 0;
435 std::list<VNCSConnectionST*>::iterator ci;
436 for (ci = clients.begin(); ci != clients.end(); ci++) {
437 if ((*ci)->authenticated())
438 count++;
439 }
440 return count;
441}
442
443inline bool VNCServerST::needRenderedCursor()
444{
445 std::list<VNCSConnectionST*>::iterator ci;
446 for (ci = clients.begin(); ci != clients.end(); ci++)
447 if ((*ci)->needRenderedCursor()) return true;
448 return false;
449}
450
451// checkUpdate() is called just before sending an update. It checks to see
452// what updates are pending and propagates them to the update tracker for each
453// client. It uses the ComparingUpdateTracker's compare() method to filter out
454// areas of the screen which haven't actually changed. It also checks the
455// state of the (server-side) rendered cursor, if necessary rendering it again
456// with the correct background.
457
458void VNCServerST::checkUpdate()
459{
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000460 UpdateInfo ui;
461 comparer->getUpdateInfo(&ui, pb->getRect());
462
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000463 bool renderCursor = needRenderedCursor();
464
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000465 if (ui.is_empty() && !(renderCursor && renderedCursorInvalid))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000466 return;
467
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000468 Region toCheck = ui.changed.union_(ui.copied).union_(ui.video_area);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000469
470 if (renderCursor) {
471 Rect clippedCursorRect
472 = cursor.getRect(cursorTL()).intersect(pb->getRect());
473
474 if (!renderedCursorInvalid && (toCheck.intersect(clippedCursorRect)
475 .is_empty())) {
476 renderCursor = false;
477 } else {
478 renderedCursorTL = clippedCursorRect.tl;
479 renderedCursor.setSize(clippedCursorRect.width(),
480 clippedCursorRect.height());
481 toCheck.assign_union(clippedCursorRect);
482 }
483 }
484
485 pb->grabRegion(toCheck);
486
487 if (rfb::Server::compareFB)
488 comparer->compare();
489
490 if (renderCursor) {
491 pb->getImage(renderedCursor.data,
492 renderedCursor.getRect(renderedCursorTL));
493 renderedCursor.maskRect(cursor.getRect(cursorTL()
494 .subtract(renderedCursorTL)),
495 cursor.data, cursor.mask.buf);
496 renderedCursorInvalid = false;
497 }
498
499 std::list<VNCSConnectionST*>::iterator ci, ci_next;
500 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
501 ci_next = ci; ci_next++;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000502 (*ci)->add_copied(ui.copied, ui.copy_delta);
503 (*ci)->add_changed(ui.changed);
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000504 (*ci)->set_video_area(ui.video_area);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000505 }
506
507 comparer->clear();
508}
509
Constantin Kaplinsky6970b2d2008-06-13 18:07:53 +0000510void VNCServerST::checkVideoUpdate()
511{
512 const Rect &videoRect = comparer->getVideoArea();
513 Region videoRegion(videoRect);
514
515 if (!videoRegion.is_empty()) {
516 pb->grabRegion(videoRegion);
517
518 std::list<VNCSConnectionST*>::iterator ci, ci_next;
519 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
520 ci_next = ci; ci_next++;
521 (*ci)->set_video_area(videoRect);
522 }
523 }
524}
525
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000526void VNCServerST::getConnInfo(ListConnInfo * listConn)
527{
528 listConn->Clear();
529 listConn->setDisable(getDisable());
530 if (clients.empty())
531 return;
532 std::list<VNCSConnectionST*>::iterator i;
533 for (i = clients.begin(); i != clients.end(); i++)
534 listConn->addInfo((void*)(*i), (*i)->getSock()->getPeerAddress(),
535 (*i)->getStartTime(), (*i)->getStatus());
536}
537
538void VNCServerST::setConnStatus(ListConnInfo* listConn)
539{
540 setDisable(listConn->getDisable());
541 if (listConn->Empty() || clients.empty()) return;
542 for (listConn->iBegin(); !listConn->iEnd(); listConn->iNext()) {
543 VNCSConnectionST* conn = (VNCSConnectionST*)listConn->iGetConn();
544 std::list<VNCSConnectionST*>::iterator i;
545 for (i = clients.begin(); i != clients.end(); i++) {
546 if ((*i) == conn) {
547 int status = listConn->iGetStatus();
548 if (status == 3) {
549 (*i)->close(0);
550 } else {
551 (*i)->setStatus(status);
552 }
553 break;
554 }
555 }
556 }
557}
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000558
559void VNCServerST::setVideoRectangle(const Rect& r)
560{
561 if (isVideoSelectionEnabled()) {
562 // FIXME: Duplication between m_videoRect and comparer->video_area.
563 m_videoRect = r;
564 set_video_area(m_videoRect);
565 }
566}
567
568void VNCServerST::unsetVideoRectangle()
569{
570 if (isVideoSelectionEnabled()) {
571 // FIXME: Duplication between m_videoRect and comparer->video_area.
572 m_videoRect.clear();
573 set_video_area(m_videoRect);
574 }
575}
576
Constantin Kaplinskyc341ac62008-08-21 03:35:08 +0000577void VNCServerST::setDefaultVideoRect(const Rect& r)
578{
579 m_defaultVideoRect = r;
580}