You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VNCServerST.cxx 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2009-2019 Pierre Ossman for Cendio AB
  3. *
  4. * This is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 2 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This software is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this software; if not, write to the Free Software
  16. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  17. * USA.
  18. */
  19. // -=- Single-Threaded VNC Server implementation
  20. // Note about how sockets get closed:
  21. //
  22. // Closing sockets to clients is non-trivial because the code which calls
  23. // VNCServerST must explicitly know about all the sockets (so that it can block
  24. // on them appropriately). However, VNCServerST may want to close clients for
  25. // a number of reasons, and from a variety of entry points. The simplest is
  26. // when processSocketEvent() is called for a client, and the remote end has
  27. // closed its socket. A more complex reason is when processSocketEvent() is
  28. // called for a client which has just sent a ClientInit with the shared flag
  29. // set to false - in this case we want to close all other clients. Yet another
  30. // reason for disconnecting clients is when the desktop size has changed as a
  31. // result of a call to setPixelBuffer().
  32. //
  33. // The responsibility for creating and deleting sockets is entirely with the
  34. // calling code. When VNCServerST wants to close a connection to a client it
  35. // calls the VNCSConnectionST's close() method which calls shutdown() on the
  36. // socket. Eventually the calling code will notice that the socket has been
  37. // shut down and call removeSocket() so that we can delete the
  38. // VNCSConnectionST. Note that the socket must not be deleted by the calling
  39. // code until after removeSocket() has been called.
  40. //
  41. // One minor complication is that we don't allocate a VNCSConnectionST object
  42. // for a blacklisted host (since we want to minimise the resources used for
  43. // dealing with such a connection). In order to properly implement the
  44. // getSockets function, we must maintain a separate closingSockets list,
  45. // otherwise blacklisted connections might be "forgotten".
  46. #ifdef HAVE_CONFIG_H
  47. #include <config.h>
  48. #endif
  49. #include <assert.h>
  50. #include <stdlib.h>
  51. #include <rfb/ComparingUpdateTracker.h>
  52. #include <rfb/Exception.h>
  53. #include <rfb/KeyRemapper.h>
  54. #include <rfb/KeysymStr.h>
  55. #include <rfb/LogWriter.h>
  56. #include <rfb/Security.h>
  57. #include <rfb/ServerCore.h>
  58. #include <rfb/VNCServerST.h>
  59. #include <rfb/VNCSConnectionST.h>
  60. #include <rfb/util.h>
  61. #include <rfb/ledStates.h>
  62. using namespace rfb;
  63. static LogWriter slog("VNCServerST");
  64. static LogWriter connectionsLog("Connections");
  65. //
  66. // -=- VNCServerST Implementation
  67. //
  68. // -=- Constructors/Destructor
  69. VNCServerST::VNCServerST(const char* name_, SDesktop* desktop_)
  70. : blHosts(&blacklist), desktop(desktop_), desktopStarted(false),
  71. blockCounter(0), pb(0), ledState(ledUnknown),
  72. name(name_), pointerClient(0), clipboardClient(0),
  73. comparer(0), cursor(new Cursor(0, 0, Point(), NULL)),
  74. renderedCursorInvalid(false),
  75. keyRemapper(&KeyRemapper::defInstance),
  76. idleTimer(this), disconnectTimer(this), connectTimer(this),
  77. frameTimer(this)
  78. {
  79. slog.debug("creating single-threaded server %s", name.c_str());
  80. // FIXME: Do we really want to kick off these right away?
  81. if (rfb::Server::maxIdleTime)
  82. idleTimer.start(secsToMillis(rfb::Server::maxIdleTime));
  83. if (rfb::Server::maxDisconnectionTime)
  84. disconnectTimer.start(secsToMillis(rfb::Server::maxDisconnectionTime));
  85. }
  86. VNCServerST::~VNCServerST()
  87. {
  88. slog.debug("shutting down server %s", name.c_str());
  89. // Close any active clients, with appropriate logging & cleanup
  90. closeClients("Server shutdown");
  91. // Stop trying to render things
  92. stopFrameClock();
  93. // Delete all the clients, and their sockets, and any closing sockets
  94. while (!clients.empty()) {
  95. VNCSConnectionST* client;
  96. client = clients.front();
  97. clients.pop_front();
  98. delete client;
  99. }
  100. // Stop the desktop object if active, *only* after deleting all clients!
  101. stopDesktop();
  102. if (comparer)
  103. comparer->logStats();
  104. delete comparer;
  105. delete cursor;
  106. }
  107. // SocketServer methods
  108. void VNCServerST::addSocket(network::Socket* sock, bool outgoing)
  109. {
  110. // - Check the connection isn't black-marked
  111. // *** do this in getSecurity instead?
  112. const char *address = sock->getPeerAddress();
  113. if (blHosts->isBlackmarked(address)) {
  114. connectionsLog.error("blacklisted: %s", address);
  115. try {
  116. rdr::OutStream& os = sock->outStream();
  117. // Shortest possible way to tell a client it is not welcome
  118. os.writeBytes((const uint8_t*)"RFB 003.003\n", 12);
  119. os.writeU32(0);
  120. const char* reason = "Too many security failures";
  121. os.writeU32(strlen(reason));
  122. os.writeBytes((const uint8_t*)reason, strlen(reason));
  123. os.flush();
  124. } catch (rdr::Exception&) {
  125. }
  126. sock->shutdown();
  127. closingSockets.push_back(sock);
  128. return;
  129. }
  130. connectionsLog.status("accepted: %s", sock->getPeerEndpoint());
  131. // Adjust the exit timers
  132. if (rfb::Server::maxConnectionTime && clients.empty())
  133. connectTimer.start(secsToMillis(rfb::Server::maxConnectionTime));
  134. disconnectTimer.stop();
  135. VNCSConnectionST* client = new VNCSConnectionST(this, sock, outgoing);
  136. clients.push_front(client);
  137. client->init();
  138. }
  139. void VNCServerST::removeSocket(network::Socket* sock) {
  140. // - If the socket has resources allocated to it, delete them
  141. std::list<VNCSConnectionST*>::iterator ci;
  142. for (ci = clients.begin(); ci != clients.end(); ci++) {
  143. if ((*ci)->getSock() == sock) {
  144. // - Remove any references to it
  145. if (pointerClient == *ci)
  146. pointerClient = NULL;
  147. if (clipboardClient == *ci)
  148. handleClipboardAnnounce(*ci, false);
  149. clipboardRequestors.remove(*ci);
  150. std::string name((*ci)->getPeerEndpoint());
  151. // - Delete the per-Socket resources
  152. delete *ci;
  153. clients.remove(*ci);
  154. connectionsLog.status("closed: %s", name.c_str());
  155. // - Check that the desktop object is still required
  156. if (authClientCount() == 0)
  157. stopDesktop();
  158. if (comparer)
  159. comparer->logStats();
  160. // Adjust the exit timers
  161. connectTimer.stop();
  162. if (rfb::Server::maxDisconnectionTime && clients.empty())
  163. disconnectTimer.start(secsToMillis(rfb::Server::maxDisconnectionTime));
  164. return;
  165. }
  166. }
  167. // - If the Socket has no resources, it may have been a closingSocket
  168. closingSockets.remove(sock);
  169. }
  170. void VNCServerST::processSocketReadEvent(network::Socket* sock)
  171. {
  172. // - Find the appropriate VNCSConnectionST and process the event
  173. std::list<VNCSConnectionST*>::iterator ci;
  174. for (ci = clients.begin(); ci != clients.end(); ci++) {
  175. if ((*ci)->getSock() == sock) {
  176. (*ci)->processMessages();
  177. return;
  178. }
  179. }
  180. throw rdr::Exception("invalid Socket in VNCServerST");
  181. }
  182. void VNCServerST::processSocketWriteEvent(network::Socket* sock)
  183. {
  184. // - Find the appropriate VNCSConnectionST and process the event
  185. std::list<VNCSConnectionST*>::iterator ci;
  186. for (ci = clients.begin(); ci != clients.end(); ci++) {
  187. if ((*ci)->getSock() == sock) {
  188. (*ci)->flushSocket();
  189. return;
  190. }
  191. }
  192. throw rdr::Exception("invalid Socket in VNCServerST");
  193. }
  194. // VNCServer methods
  195. void VNCServerST::blockUpdates()
  196. {
  197. blockCounter++;
  198. stopFrameClock();
  199. }
  200. void VNCServerST::unblockUpdates()
  201. {
  202. assert(blockCounter > 0);
  203. blockCounter--;
  204. // Restart the frame clock if we have updates
  205. if (blockCounter == 0) {
  206. if (!comparer->is_empty())
  207. startFrameClock();
  208. }
  209. }
  210. void VNCServerST::setPixelBuffer(PixelBuffer* pb_, const ScreenSet& layout)
  211. {
  212. if (comparer)
  213. comparer->logStats();
  214. pb = pb_;
  215. delete comparer;
  216. comparer = 0;
  217. if (!pb) {
  218. screenLayout = ScreenSet();
  219. if (desktopStarted)
  220. throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
  221. return;
  222. }
  223. if (!layout.validate(pb->width(), pb->height()))
  224. throw Exception("setPixelBuffer: invalid screen layout");
  225. screenLayout = layout;
  226. // Assume the framebuffer contents wasn't saved and reset everything
  227. // that tracks its contents
  228. comparer = new ComparingUpdateTracker(pb);
  229. renderedCursorInvalid = true;
  230. add_changed(pb->getRect());
  231. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  232. for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
  233. ci_next = ci; ci_next++;
  234. (*ci)->pixelBufferChange();
  235. // Since the new pixel buffer means an ExtendedDesktopSize needs to
  236. // be sent anyway, we don't need to call screenLayoutChange.
  237. }
  238. }
  239. void VNCServerST::setPixelBuffer(PixelBuffer* pb_)
  240. {
  241. ScreenSet layout = screenLayout;
  242. // Check that the screen layout is still valid
  243. if (pb_ && !layout.validate(pb_->width(), pb_->height())) {
  244. Rect fbRect;
  245. ScreenSet::iterator iter, iter_next;
  246. fbRect.setXYWH(0, 0, pb_->width(), pb_->height());
  247. for (iter = layout.begin();iter != layout.end();iter = iter_next) {
  248. iter_next = iter; ++iter_next;
  249. if (iter->dimensions.enclosed_by(fbRect))
  250. continue;
  251. iter->dimensions = iter->dimensions.intersect(fbRect);
  252. if (iter->dimensions.is_empty()) {
  253. slog.info("Removing screen %d (%x) as it is completely outside the new framebuffer",
  254. (int)iter->id, (unsigned)iter->id);
  255. layout.remove_screen(iter->id);
  256. }
  257. }
  258. }
  259. // Make sure that we have at least one screen
  260. if (layout.num_screens() == 0)
  261. layout.add_screen(Screen(0, 0, 0, pb_->width(), pb_->height(), 0));
  262. setPixelBuffer(pb_, layout);
  263. }
  264. void VNCServerST::setScreenLayout(const ScreenSet& layout)
  265. {
  266. if (!pb)
  267. throw Exception("setScreenLayout: new screen layout without a PixelBuffer");
  268. if (!layout.validate(pb->width(), pb->height()))
  269. throw Exception("setScreenLayout: invalid screen layout");
  270. screenLayout = layout;
  271. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  272. for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
  273. ci_next = ci; ci_next++;
  274. (*ci)->screenLayoutChangeOrClose(reasonServer);
  275. }
  276. }
  277. void VNCServerST::requestClipboard()
  278. {
  279. if (clipboardClient == NULL) {
  280. slog.debug("Got request for client clipboard but no client currently owns the clipboard");
  281. return;
  282. }
  283. clipboardClient->requestClipboardOrClose();
  284. }
  285. void VNCServerST::announceClipboard(bool available)
  286. {
  287. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  288. clipboardRequestors.clear();
  289. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  290. ci_next = ci; ci_next++;
  291. (*ci)->announceClipboardOrClose(available);
  292. }
  293. }
  294. void VNCServerST::sendClipboardData(const char* data)
  295. {
  296. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  297. if (strchr(data, '\r') != NULL)
  298. throw Exception("Invalid carriage return in clipboard data");
  299. for (ci = clipboardRequestors.begin();
  300. ci != clipboardRequestors.end(); ci = ci_next) {
  301. ci_next = ci; ci_next++;
  302. (*ci)->sendClipboardDataOrClose(data);
  303. }
  304. clipboardRequestors.clear();
  305. }
  306. void VNCServerST::bell()
  307. {
  308. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  309. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  310. ci_next = ci; ci_next++;
  311. (*ci)->bellOrClose();
  312. }
  313. }
  314. void VNCServerST::setName(const char* name_)
  315. {
  316. name = name_;
  317. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  318. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  319. ci_next = ci; ci_next++;
  320. (*ci)->setDesktopNameOrClose(name_);
  321. }
  322. }
  323. void VNCServerST::add_changed(const Region& region)
  324. {
  325. if (comparer == NULL)
  326. return;
  327. comparer->add_changed(region);
  328. startFrameClock();
  329. }
  330. void VNCServerST::add_copied(const Region& dest, const Point& delta)
  331. {
  332. if (comparer == NULL)
  333. return;
  334. comparer->add_copied(dest, delta);
  335. startFrameClock();
  336. }
  337. void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
  338. const uint8_t* data)
  339. {
  340. delete cursor;
  341. cursor = new Cursor(width, height, newHotspot, data);
  342. cursor->crop();
  343. renderedCursorInvalid = true;
  344. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  345. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  346. ci_next = ci; ci_next++;
  347. (*ci)->renderedCursorChange();
  348. (*ci)->setCursorOrClose();
  349. }
  350. }
  351. void VNCServerST::setCursorPos(const Point& pos, bool warped)
  352. {
  353. if (cursorPos != pos) {
  354. cursorPos = pos;
  355. renderedCursorInvalid = true;
  356. std::list<VNCSConnectionST*>::iterator ci;
  357. for (ci = clients.begin(); ci != clients.end(); ci++) {
  358. (*ci)->renderedCursorChange();
  359. if (warped)
  360. (*ci)->cursorPositionChange();
  361. }
  362. }
  363. }
  364. void VNCServerST::setLEDState(unsigned int state)
  365. {
  366. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  367. if (state == ledState)
  368. return;
  369. ledState = state;
  370. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  371. ci_next = ci; ci_next++;
  372. (*ci)->setLEDStateOrClose(state);
  373. }
  374. }
  375. // Event handlers
  376. void VNCServerST::keyEvent(uint32_t keysym, uint32_t keycode, bool down)
  377. {
  378. if (rfb::Server::maxIdleTime)
  379. idleTimer.start(secsToMillis(rfb::Server::maxIdleTime));
  380. // Remap the key if required
  381. if (keyRemapper) {
  382. uint32_t newkey;
  383. newkey = keyRemapper->remapKey(keysym);
  384. if (newkey != keysym) {
  385. slog.debug("Key remapped to XK_%s (0x%x)",
  386. KeySymName(newkey), newkey);
  387. keysym = newkey;
  388. }
  389. }
  390. desktop->keyEvent(keysym, keycode, down);
  391. }
  392. void VNCServerST::pointerEvent(VNCSConnectionST* client,
  393. const Point& pos, int buttonMask)
  394. {
  395. if (rfb::Server::maxIdleTime)
  396. idleTimer.start(secsToMillis(rfb::Server::maxIdleTime));
  397. // Let one client own the cursor whilst buttons are pressed in order
  398. // to provide a bit more sane user experience
  399. if ((pointerClient != NULL) && (pointerClient != client))
  400. return;
  401. if (buttonMask)
  402. pointerClient = client;
  403. else
  404. pointerClient = NULL;
  405. desktop->pointerEvent(pos, buttonMask);
  406. }
  407. void VNCServerST::handleClipboardRequest(VNCSConnectionST* client)
  408. {
  409. clipboardRequestors.push_back(client);
  410. if (clipboardRequestors.size() == 1)
  411. desktop->handleClipboardRequest();
  412. }
  413. void VNCServerST::handleClipboardAnnounce(VNCSConnectionST* client,
  414. bool available)
  415. {
  416. if (available)
  417. clipboardClient = client;
  418. else {
  419. if (client != clipboardClient)
  420. return;
  421. clipboardClient = NULL;
  422. }
  423. desktop->handleClipboardAnnounce(available);
  424. }
  425. void VNCServerST::handleClipboardData(VNCSConnectionST* client,
  426. const char* data)
  427. {
  428. if (client != clipboardClient) {
  429. slog.debug("Ignoring unexpected clipboard data");
  430. return;
  431. }
  432. desktop->handleClipboardData(data);
  433. }
  434. unsigned int VNCServerST::setDesktopSize(VNCSConnectionST* requester,
  435. int fb_width, int fb_height,
  436. const ScreenSet& layout)
  437. {
  438. unsigned int result;
  439. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  440. // We can't handle a framebuffer larger than this, so don't let a
  441. // client set one (see PixelBuffer.cxx)
  442. if ((fb_width > 16384) || (fb_height > 16384)) {
  443. slog.error("Rejecting too large framebuffer resize request");
  444. return resultProhibited;
  445. }
  446. // Don't bother the desktop with an invalid configuration
  447. if (!layout.validate(fb_width, fb_height)) {
  448. slog.error("Invalid screen layout requested by client");
  449. return resultInvalid;
  450. }
  451. // FIXME: the desktop will call back to VNCServerST and an extra set
  452. // of ExtendedDesktopSize messages will be sent. This is okay
  453. // protocol-wise, but unnecessary.
  454. result = desktop->setScreenLayout(fb_width, fb_height, layout);
  455. if (result != resultSuccess)
  456. return result;
  457. // Sanity check
  458. if (screenLayout != layout)
  459. throw Exception("Desktop configured a different screen layout than requested");
  460. // Notify other clients
  461. for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
  462. ci_next = ci; ci_next++;
  463. if ((*ci) == requester)
  464. continue;
  465. (*ci)->screenLayoutChangeOrClose(reasonOtherClient);
  466. }
  467. return resultSuccess;
  468. }
  469. // Other public methods
  470. void VNCServerST::approveConnection(network::Socket* sock, bool accept,
  471. const char* reason)
  472. {
  473. std::list<VNCSConnectionST*>::iterator ci;
  474. for (ci = clients.begin(); ci != clients.end(); ci++) {
  475. if ((*ci)->getSock() == sock) {
  476. (*ci)->approveConnectionOrClose(accept, reason);
  477. return;
  478. }
  479. }
  480. }
  481. void VNCServerST::closeClients(const char* reason, network::Socket* except)
  482. {
  483. std::list<VNCSConnectionST*>::iterator i, next_i;
  484. for (i=clients.begin(); i!=clients.end(); i=next_i) {
  485. next_i = i; next_i++;
  486. if ((*i)->getSock() != except)
  487. (*i)->close(reason);
  488. }
  489. }
  490. void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
  491. {
  492. sockets->clear();
  493. std::list<VNCSConnectionST*>::iterator ci;
  494. for (ci = clients.begin(); ci != clients.end(); ci++) {
  495. sockets->push_back((*ci)->getSock());
  496. }
  497. std::list<network::Socket*>::iterator si;
  498. for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
  499. sockets->push_back(*si);
  500. }
  501. }
  502. SConnection* VNCServerST::getConnection(network::Socket* sock) {
  503. std::list<VNCSConnectionST*>::iterator ci;
  504. for (ci = clients.begin(); ci != clients.end(); ci++) {
  505. if ((*ci)->getSock() == sock)
  506. return (SConnection*)*ci;
  507. }
  508. return 0;
  509. }
  510. bool VNCServerST::handleTimeout(Timer* t)
  511. {
  512. if (t == &frameTimer) {
  513. // We keep running until we go a full interval without any updates
  514. if (comparer->is_empty())
  515. return false;
  516. writeUpdate();
  517. // If this is the first iteration then we need to adjust the timeout
  518. if (frameTimer.getTimeoutMs() != 1000/rfb::Server::frameRate) {
  519. frameTimer.start(1000/rfb::Server::frameRate);
  520. return false;
  521. }
  522. return true;
  523. } else if (t == &idleTimer) {
  524. slog.info("MaxIdleTime reached, exiting");
  525. desktop->terminate();
  526. } else if (t == &disconnectTimer) {
  527. slog.info("MaxDisconnectionTime reached, exiting");
  528. desktop->terminate();
  529. } else if (t == &connectTimer) {
  530. slog.info("MaxConnectionTime reached, exiting");
  531. desktop->terminate();
  532. }
  533. return false;
  534. }
  535. void VNCServerST::queryConnection(VNCSConnectionST* client,
  536. const char* userName)
  537. {
  538. // - Authentication succeeded - clear from blacklist
  539. blHosts->clearBlackmark(client->getSock()->getPeerAddress());
  540. // - Prepare the desktop for that the client will start requiring
  541. // resources after this
  542. startDesktop();
  543. // - Special case to provide a more useful error message
  544. if (rfb::Server::neverShared &&
  545. !rfb::Server::disconnectClients &&
  546. authClientCount() > 0) {
  547. approveConnection(client->getSock(), false,
  548. "The server is already in use");
  549. return;
  550. }
  551. // - Are we configured to do queries?
  552. if (!rfb::Server::queryConnect &&
  553. !client->getSock()->requiresQuery()) {
  554. approveConnection(client->getSock(), true, NULL);
  555. return;
  556. }
  557. // - Does the client have the right to bypass the query?
  558. if (client->accessCheck(SConnection::AccessNoQuery))
  559. {
  560. approveConnection(client->getSock(), true, NULL);
  561. return;
  562. }
  563. desktop->queryConnection(client->getSock(), userName);
  564. }
  565. void VNCServerST::clientReady(VNCSConnectionST* client, bool shared)
  566. {
  567. if (!shared) {
  568. if (rfb::Server::disconnectClients &&
  569. client->accessCheck(SConnection::AccessNonShared)) {
  570. // - Close all the other connected clients
  571. slog.debug("non-shared connection - closing clients");
  572. closeClients("Non-shared connection requested", client->getSock());
  573. } else {
  574. // - Refuse this connection if there are existing clients, in addition to
  575. // this one
  576. if (authClientCount() > 1) {
  577. client->close("Server is already in use");
  578. return;
  579. }
  580. }
  581. }
  582. }
  583. // -=- Internal methods
  584. void VNCServerST::startDesktop()
  585. {
  586. if (!desktopStarted) {
  587. slog.debug("starting desktop");
  588. desktop->start(this);
  589. if (!pb)
  590. throw Exception("SDesktop::start() did not set a valid PixelBuffer");
  591. desktopStarted = true;
  592. // The tracker might have accumulated changes whilst we were
  593. // stopped, so flush those out
  594. if (!comparer->is_empty())
  595. writeUpdate();
  596. }
  597. }
  598. void VNCServerST::stopDesktop()
  599. {
  600. if (desktopStarted) {
  601. slog.debug("stopping desktop");
  602. desktopStarted = false;
  603. desktop->stop();
  604. stopFrameClock();
  605. }
  606. }
  607. int VNCServerST::authClientCount() {
  608. int count = 0;
  609. std::list<VNCSConnectionST*>::iterator ci;
  610. for (ci = clients.begin(); ci != clients.end(); ci++) {
  611. if ((*ci)->authenticated())
  612. count++;
  613. }
  614. return count;
  615. }
  616. inline bool VNCServerST::needRenderedCursor()
  617. {
  618. std::list<VNCSConnectionST*>::iterator ci;
  619. for (ci = clients.begin(); ci != clients.end(); ci++)
  620. if ((*ci)->needRenderedCursor()) return true;
  621. return false;
  622. }
  623. void VNCServerST::startFrameClock()
  624. {
  625. if (frameTimer.isStarted())
  626. return;
  627. if (blockCounter > 0)
  628. return;
  629. if (!desktopStarted)
  630. return;
  631. // The first iteration will be just half a frame as we get a very
  632. // unstable update rate if we happen to be perfectly in sync with
  633. // the application's update rate
  634. frameTimer.start(1000/rfb::Server::frameRate/2);
  635. }
  636. void VNCServerST::stopFrameClock()
  637. {
  638. frameTimer.stop();
  639. }
  640. int VNCServerST::msToNextUpdate()
  641. {
  642. // FIXME: If the application is updating slower than frameRate then
  643. // we could allow the clients more time here
  644. if (!frameTimer.isStarted())
  645. return 1000/rfb::Server::frameRate/2;
  646. else
  647. return frameTimer.getRemainingMs();
  648. }
  649. // writeUpdate() is called on a regular interval in order to see what
  650. // updates are pending and propagates them to the update tracker for
  651. // each client. It uses the ComparingUpdateTracker's compare() method
  652. // to filter out areas of the screen which haven't actually changed. It
  653. // also checks the state of the (server-side) rendered cursor, if
  654. // necessary rendering it again with the correct background.
  655. void VNCServerST::writeUpdate()
  656. {
  657. UpdateInfo ui;
  658. Region toCheck;
  659. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  660. assert(blockCounter == 0);
  661. assert(desktopStarted);
  662. comparer->getUpdateInfo(&ui, pb->getRect());
  663. toCheck = ui.changed.union_(ui.copied);
  664. if (needRenderedCursor()) {
  665. Rect clippedCursorRect = Rect(0, 0, cursor->width(), cursor->height())
  666. .translate(cursorPos.subtract(cursor->hotspot()))
  667. .intersect(pb->getRect());
  668. if (!toCheck.intersect(clippedCursorRect).is_empty())
  669. renderedCursorInvalid = true;
  670. }
  671. pb->grabRegion(toCheck);
  672. if (getComparerState())
  673. comparer->enable();
  674. else
  675. comparer->disable();
  676. if (comparer->compare())
  677. comparer->getUpdateInfo(&ui, pb->getRect());
  678. comparer->clear();
  679. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  680. ci_next = ci; ci_next++;
  681. (*ci)->add_copied(ui.copied, ui.copy_delta);
  682. (*ci)->add_changed(ui.changed);
  683. (*ci)->writeFramebufferUpdateOrClose();
  684. }
  685. }
  686. // checkUpdate() is called by clients to see if it is safe to read from
  687. // the framebuffer at this time.
  688. Region VNCServerST::getPendingRegion()
  689. {
  690. UpdateInfo ui;
  691. // Block clients as the frame buffer cannot be safely accessed
  692. if (blockCounter > 0)
  693. return pb->getRect();
  694. // Block client from updating if there are pending updates
  695. if (comparer->is_empty())
  696. return Region();
  697. comparer->getUpdateInfo(&ui, pb->getRect());
  698. return ui.changed.union_(ui.copied);
  699. }
  700. const RenderedCursor* VNCServerST::getRenderedCursor()
  701. {
  702. if (renderedCursorInvalid) {
  703. renderedCursor.update(pb, cursor, cursorPos);
  704. renderedCursorInvalid = false;
  705. }
  706. return &renderedCursor;
  707. }
  708. bool VNCServerST::getComparerState()
  709. {
  710. if (rfb::Server::compareFB == 0)
  711. return false;
  712. if (rfb::Server::compareFB != 2)
  713. return true;
  714. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  715. for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
  716. ci_next = ci; ci_next++;
  717. if ((*ci)->getComparerState())
  718. return true;
  719. }
  720. return false;
  721. }