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 23KB

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