blob: a21526ad7b19bff2a6b1f4cbe9401fcf46c9760e [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
Pierre Ossmanf99c5712009-03-13 14:41:27 +000050#include <stdlib.h>
51
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000052#include <rfb/ServerCore.h>
53#include <rfb/VNCServerST.h>
54#include <rfb/VNCSConnectionST.h>
55#include <rfb/ComparingUpdateTracker.h>
56#include <rfb/SSecurityFactoryStandard.h>
57#include <rfb/KeyRemapper.h>
58#include <rfb/util.h>
59
60#include <rdr/types.h>
61
62using namespace rfb;
63
64static LogWriter slog("VNCServerST");
65LogWriter VNCServerST::connectionsLog("Connections");
66static SSecurityFactoryStandard defaultSecurityFactory;
67
68//
69// -=- VNCServerST Implementation
70//
71
72// -=- Constructors/Destructor
73
74VNCServerST::VNCServerST(const char* name_, SDesktop* desktop_,
75 SSecurityFactory* sf)
76 : blHosts(&blacklist), desktop(desktop_), desktopStarted(false), pb(0),
Pierre Ossmanf99c5712009-03-13 14:41:27 +000077 name(strDup(name_)), pointerClient(0), comparer(0),
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000078 renderedCursorInvalid(false),
79 securityFactory(sf ? sf : &defaultSecurityFactory),
80 queryConnectionHandler(0), keyRemapper(&KeyRemapper::defInstance),
81 useEconomicTranslate(false),
Pierre Ossman02e43d72009-03-05 11:57:11 +000082 lastConnectionTime(0), disableclients(false)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000083{
84 lastUserInputTime = lastDisconnectTime = time(0);
85 slog.debug("creating single-threaded server %s", name.buf);
86}
87
88VNCServerST::~VNCServerST()
89{
90 slog.debug("shutting down server %s", name.buf);
91
92 // Close any active clients, with appropriate logging & cleanup
93 closeClients("Server shutdown");
94
95 // Delete all the clients, and their sockets, and any closing sockets
96 // NB: Deleting a client implicitly removes it from the clients list
97 while (!clients.empty()) {
98 delete clients.front();
99 }
100
101 // Stop the desktop object if active, *only* after deleting all clients!
102 if (desktopStarted) {
103 desktopStarted = false;
104 desktop->stop();
105 }
106
107 delete comparer;
108}
109
110
111// SocketServer methods
112
113void VNCServerST::addSocket(network::Socket* sock, bool outgoing)
114{
115 // - Check the connection isn't black-marked
116 // *** do this in getSecurity instead?
117 CharArray address(sock->getPeerAddress());
118 if (blHosts->isBlackmarked(address.buf)) {
119 connectionsLog.error("blacklisted: %s", address.buf);
120 try {
121 SConnection::writeConnFailedFromScratch("Too many security failures",
122 &sock->outStream());
123 } catch (rdr::Exception&) {
124 }
125 sock->shutdown();
126 closingSockets.push_back(sock);
127 return;
128 }
129
130 if (clients.empty()) {
131 lastConnectionTime = time(0);
132 }
133
134 VNCSConnectionST* client = new VNCSConnectionST(this, sock, outgoing);
135 client->init();
136}
137
138void VNCServerST::removeSocket(network::Socket* sock) {
139 // - If the socket has resources allocated to it, delete them
140 std::list<VNCSConnectionST*>::iterator ci;
141 for (ci = clients.begin(); ci != clients.end(); ci++) {
142 if ((*ci)->getSock() == sock) {
143 // - Delete the per-Socket resources
144 delete *ci;
145
146 // - Check that the desktop object is still required
147 if (authClientCount() == 0 && desktopStarted) {
148 slog.debug("no authenticated clients - stopping desktop");
149 desktopStarted = false;
150 desktop->stop();
151 }
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
Pierre Ossman04e62db2009-03-23 16:57:07 +0000255void VNCServerST::setPixelBuffer(PixelBuffer* pb_, const ScreenSet& layout)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000256{
257 pb = pb_;
258 delete comparer;
259 comparer = 0;
260
Pierre Ossman04e62db2009-03-23 16:57:07 +0000261 screenLayout = layout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000262
Pierre Ossman04e62db2009-03-23 16:57:07 +0000263 if (!pb) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000264 if (desktopStarted)
265 throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
Pierre Ossman04e62db2009-03-23 16:57:07 +0000266 return;
267 }
268
269 comparer = new ComparingUpdateTracker(pb);
270 cursor.setPF(pb->getPF());
271 renderedCursor.setPF(pb->getPF());
272
273 // Make sure that we have at least one screen
274 if (screenLayout.num_screens() == 0)
275 screenLayout.add_screen(Screen(0, 0, 0, pb->width(), pb->height(), 0));
276
277 std::list<VNCSConnectionST*>::iterator ci, ci_next;
278 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
279 ci_next = ci; ci_next++;
280 (*ci)->pixelBufferChange();
281 // Since the new pixel buffer means an ExtendedDesktopSize needs to
282 // be sent anyway, we don't need to call screenLayoutChange.
283 }
284}
285
286void VNCServerST::setPixelBuffer(PixelBuffer* pb_)
287{
288 ScreenSet layout;
289
290 if (!pb_) {
291 if (desktopStarted)
292 throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
293 return;
294 }
295
296 layout = screenLayout;
297
298 // Check that the screen layout is still valid
299 if (!layout.validate(pb_->width(), pb_->height())) {
300 Rect fbRect;
301 ScreenSet::iterator iter, iter_next;
302
303 fbRect.setXYWH(0, 0, pb_->width(), pb_->height());
304
305 for (iter = layout.begin();iter != layout.end();iter = iter_next) {
306 iter_next = iter; ++iter_next;
307 if (iter->dimensions.enclosed_by(fbRect))
308 continue;
309 iter->dimensions = iter->dimensions.intersect(fbRect);
310 if (iter->dimensions.is_empty()) {
311 slog.info("Removing screen %d (%x) as it is completely outside the new framebuffer",
312 (int)iter->id, (unsigned)iter->id);
313 layout.remove_screen(iter->id);
314 }
315 }
316 }
317
318 setPixelBuffer(pb_, layout);
319}
320
321void VNCServerST::setScreenLayout(const ScreenSet& layout)
322{
323 if (!pb)
324 throw Exception("setScreenLayout: new screen layout without a PixelBuffer");
325 if (!layout.validate(pb->width(), pb->height()))
326 throw Exception("setScreenLayout: invalid screen layout");
327
Pierre Ossmandf453202009-04-02 14:26:45 +0000328 screenLayout = layout;
329
Pierre Ossman04e62db2009-03-23 16:57:07 +0000330 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)->screenLayoutChange(reasonServer);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000334 }
335}
336
337void VNCServerST::setColourMapEntries(int firstColour, int nColours)
338{
339 std::list<VNCSConnectionST*>::iterator ci, ci_next;
340 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
341 ci_next = ci; ci_next++;
342 (*ci)->setColourMapEntriesOrClose(firstColour, nColours);
343 }
344}
345
346void VNCServerST::bell()
347{
348 std::list<VNCSConnectionST*>::iterator ci, ci_next;
349 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
350 ci_next = ci; ci_next++;
351 (*ci)->bell();
352 }
353}
354
355void VNCServerST::serverCutText(const char* str, int len)
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)->serverCutText(str, len);
361 }
362}
363
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000364void VNCServerST::setName(const char* name_)
365{
366 name.replaceBuf(strDup(name_));
367 std::list<VNCSConnectionST*>::iterator ci, ci_next;
368 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
369 ci_next = ci; ci_next++;
370 (*ci)->setDesktopName(name_);
371 }
372}
373
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000374void VNCServerST::add_changed(const Region& region)
375{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000376 if (comparer != 0) {
377 comparer->add_changed(region);
378 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000379}
380
381void VNCServerST::add_copied(const Region& dest, const Point& delta)
382{
Constantin Kaplinsky3ce6a722008-09-05 02:26:35 +0000383 if (comparer != 0) {
384 comparer->add_copied(dest, delta);
385 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000386}
387
388bool VNCServerST::clientsReadyForUpdate()
389{
390 std::list<VNCSConnectionST*>::iterator ci;
391 for (ci = clients.begin(); ci != clients.end(); ci++) {
392 if ((*ci)->readyForUpdate())
393 return true;
394 }
395 return false;
396}
397
398void VNCServerST::tryUpdate()
399{
400 std::list<VNCSConnectionST*>::iterator ci, ci_next;
401 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
402 ci_next = ci; ci_next++;
403 (*ci)->writeFramebufferUpdateOrClose();
404 }
405}
406
407void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
408 void* data, void* mask)
409{
410 cursor.hotspot = newHotspot;
411 cursor.setSize(width, height);
412 memcpy(cursor.data, data, cursor.dataLen());
413 memcpy(cursor.mask.buf, mask, cursor.maskLen());
414
415 cursor.crop();
416
417 renderedCursorInvalid = true;
418
419 std::list<VNCSConnectionST*>::iterator ci, ci_next;
420 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
421 ci_next = ci; ci_next++;
422 (*ci)->renderedCursorChange();
423 (*ci)->setCursorOrClose();
424 }
425}
426
427void VNCServerST::setCursorPos(const Point& pos)
428{
429 if (!cursorPos.equals(pos)) {
430 cursorPos = pos;
431 renderedCursorInvalid = true;
432 std::list<VNCSConnectionST*>::iterator ci;
433 for (ci = clients.begin(); ci != clients.end(); ci++)
434 (*ci)->renderedCursorChange();
435 }
436}
437
438// Other public methods
439
440void VNCServerST::approveConnection(network::Socket* sock, bool accept,
441 const char* reason)
442{
443 std::list<VNCSConnectionST*>::iterator ci;
444 for (ci = clients.begin(); ci != clients.end(); ci++) {
445 if ((*ci)->getSock() == sock) {
446 (*ci)->approveConnectionOrClose(accept, reason);
447 return;
448 }
449 }
450}
451
452void VNCServerST::closeClients(const char* reason, network::Socket* except)
453{
454 std::list<VNCSConnectionST*>::iterator i, next_i;
455 for (i=clients.begin(); i!=clients.end(); i=next_i) {
456 next_i = i; next_i++;
457 if ((*i)->getSock() != except)
458 (*i)->close(reason);
459 }
460}
461
462void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
463{
464 sockets->clear();
465 std::list<VNCSConnectionST*>::iterator ci;
466 for (ci = clients.begin(); ci != clients.end(); ci++) {
467 sockets->push_back((*ci)->getSock());
468 }
469 std::list<network::Socket*>::iterator si;
470 for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
471 sockets->push_back(*si);
472 }
473}
474
475SConnection* VNCServerST::getSConnection(network::Socket* sock) {
476 std::list<VNCSConnectionST*>::iterator ci;
477 for (ci = clients.begin(); ci != clients.end(); ci++) {
478 if ((*ci)->getSock() == sock)
479 return *ci;
480 }
481 return 0;
482}
483
484
485// -=- Internal methods
486
487void VNCServerST::startDesktop()
488{
489 if (!desktopStarted) {
490 slog.debug("starting desktop");
491 desktop->start(this);
492 desktopStarted = true;
493 if (!pb)
494 throw Exception("SDesktop::start() did not set a valid PixelBuffer");
495 }
496}
497
498int VNCServerST::authClientCount() {
499 int count = 0;
500 std::list<VNCSConnectionST*>::iterator ci;
501 for (ci = clients.begin(); ci != clients.end(); ci++) {
502 if ((*ci)->authenticated())
503 count++;
504 }
505 return count;
506}
507
508inline bool VNCServerST::needRenderedCursor()
509{
510 std::list<VNCSConnectionST*>::iterator ci;
511 for (ci = clients.begin(); ci != clients.end(); ci++)
512 if ((*ci)->needRenderedCursor()) return true;
513 return false;
514}
515
516// checkUpdate() is called just before sending an update. It checks to see
517// what updates are pending and propagates them to the update tracker for each
518// client. It uses the ComparingUpdateTracker's compare() method to filter out
519// areas of the screen which haven't actually changed. It also checks the
520// state of the (server-side) rendered cursor, if necessary rendering it again
521// with the correct background.
522
523void VNCServerST::checkUpdate()
524{
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000525 UpdateInfo ui;
526 comparer->getUpdateInfo(&ui, pb->getRect());
527
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000528 bool renderCursor = needRenderedCursor();
529
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000530 if (ui.is_empty() && !(renderCursor && renderedCursorInvalid))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000531 return;
532
Pierre Ossman02e43d72009-03-05 11:57:11 +0000533 Region toCheck = ui.changed.union_(ui.copied);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000534
535 if (renderCursor) {
536 Rect clippedCursorRect
537 = cursor.getRect(cursorTL()).intersect(pb->getRect());
538
539 if (!renderedCursorInvalid && (toCheck.intersect(clippedCursorRect)
540 .is_empty())) {
541 renderCursor = false;
542 } else {
543 renderedCursorTL = clippedCursorRect.tl;
544 renderedCursor.setSize(clippedCursorRect.width(),
545 clippedCursorRect.height());
546 toCheck.assign_union(clippedCursorRect);
547 }
548 }
549
550 pb->grabRegion(toCheck);
551
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000552 if (rfb::Server::compareFB) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000553 comparer->compare();
Constantin Kaplinskyf0b3be72008-08-21 05:22:04 +0000554 comparer->getUpdateInfo(&ui, pb->getRect());
555 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000556
557 if (renderCursor) {
558 pb->getImage(renderedCursor.data,
559 renderedCursor.getRect(renderedCursorTL));
560 renderedCursor.maskRect(cursor.getRect(cursorTL()
561 .subtract(renderedCursorTL)),
562 cursor.data, cursor.mask.buf);
563 renderedCursorInvalid = false;
564 }
565
566 std::list<VNCSConnectionST*>::iterator ci, ci_next;
567 for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
568 ci_next = ci; ci_next++;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000569 (*ci)->add_copied(ui.copied, ui.copy_delta);
570 (*ci)->add_changed(ui.changed);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000571 }
572
573 comparer->clear();
574}
575
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000576void VNCServerST::getConnInfo(ListConnInfo * listConn)
577{
578 listConn->Clear();
579 listConn->setDisable(getDisable());
580 if (clients.empty())
581 return;
582 std::list<VNCSConnectionST*>::iterator i;
583 for (i = clients.begin(); i != clients.end(); i++)
584 listConn->addInfo((void*)(*i), (*i)->getSock()->getPeerAddress(),
585 (*i)->getStartTime(), (*i)->getStatus());
586}
587
588void VNCServerST::setConnStatus(ListConnInfo* listConn)
589{
590 setDisable(listConn->getDisable());
591 if (listConn->Empty() || clients.empty()) return;
592 for (listConn->iBegin(); !listConn->iEnd(); listConn->iNext()) {
593 VNCSConnectionST* conn = (VNCSConnectionST*)listConn->iGetConn();
594 std::list<VNCSConnectionST*>::iterator i;
595 for (i = clients.begin(); i != clients.end(); i++) {
596 if ((*i) == conn) {
597 int status = listConn->iGetStatus();
598 if (status == 3) {
599 (*i)->close(0);
600 } else {
601 (*i)->setStatus(status);
602 }
603 break;
604 }
605 }
606 }
607}
Constantin Kaplinsky9d1fc6c2008-06-14 05:23:10 +0000608
Pierre Ossman04e62db2009-03-23 16:57:07 +0000609void VNCServerST::notifyScreenLayoutChange(VNCSConnectionST* requester)
610{
611 std::list<VNCSConnectionST*>::iterator ci, ci_next;
612 for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
613 ci_next = ci; ci_next++;
614 if ((*ci) == requester)
615 continue;
616 (*ci)->screenLayoutChange(reasonOtherClient);
617 }
618}