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

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