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

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