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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. #include <rdr/types.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(strDup(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.buf);
  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.buf);
  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. CharArray address(sock->getPeerAddress());
  112. if (blHosts->isBlackmarked(address.buf)) {
  113. connectionsLog.error("blacklisted: %s", address.buf);
  114. try {
  115. rdr::OutStream& os = sock->outStream();
  116. // Shortest possible way to tell a client it is not welcome
  117. os.writeBytes("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(reason, strlen(reason));
  122. os.flush();
  123. } catch (rdr::Exception&) {
  124. }
  125. sock->shutdown();
  126. closingSockets.push_back(sock);
  127. return;
  128. }
  129. CharArray name;
  130. name.buf = sock->getPeerEndpoint();
  131. connectionsLog.status("accepted: %s", name.buf);
  132. // Adjust the exit timers
  133. if (rfb::Server::maxConnectionTime && clients.empty())
  134. connectTimer.start(secsToMillis(rfb::Server::maxConnectionTime));
  135. disconnectTimer.stop();
  136. VNCSConnectionST* client = new VNCSConnectionST(this, sock, outgoing);
  137. clients.push_front(client);
  138. client->init();
  139. }
  140. void VNCServerST::removeSocket(network::Socket* sock) {
  141. // - If the socket has resources allocated to it, delete them
  142. std::list<VNCSConnectionST*>::iterator ci;
  143. for (ci = clients.begin(); ci != clients.end(); ci++) {
  144. if ((*ci)->getSock() == sock) {
  145. // - Remove any references to it
  146. if (pointerClient == *ci)
  147. pointerClient = NULL;
  148. if (clipboardClient == *ci)
  149. handleClipboardAnnounce(*ci, false);
  150. clipboardRequestors.remove(*ci);
  151. CharArray name(strDup((*ci)->getPeerEndpoint()));
  152. // - Delete the per-Socket resources
  153. delete *ci;
  154. clients.remove(*ci);
  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. // Adjust the exit timers
  162. connectTimer.stop();
  163. if (rfb::Server::maxDisconnectionTime && clients.empty())
  164. disconnectTimer.start(secsToMillis(rfb::Server::maxDisconnectionTime));
  165. return;
  166. }
  167. }
  168. // - If the Socket has no resources, it may have been a closingSocket
  169. closingSockets.remove(sock);
  170. }
  171. void VNCServerST::processSocketReadEvent(network::Socket* sock)
  172. {
  173. // - Find the appropriate VNCSConnectionST and process the event
  174. std::list<VNCSConnectionST*>::iterator ci;
  175. for (ci = clients.begin(); ci != clients.end(); ci++) {
  176. if ((*ci)->getSock() == sock) {
  177. (*ci)->processMessages();
  178. return;
  179. }
  180. }
  181. throw rdr::Exception("invalid Socket in VNCServerST");
  182. }
  183. void VNCServerST::processSocketWriteEvent(network::Socket* sock)
  184. {
  185. // - Find the appropriate VNCSConnectionST and process the event
  186. std::list<VNCSConnectionST*>::iterator ci;
  187. for (ci = clients.begin(); ci != clients.end(); ci++) {
  188. if ((*ci)->getSock() == sock) {
  189. (*ci)->flushSocket();
  190. return;
  191. }
  192. }
  193. throw rdr::Exception("invalid Socket in VNCServerST");
  194. }
  195. // VNCServer methods
  196. void VNCServerST::blockUpdates()
  197. {
  198. blockCounter++;
  199. stopFrameClock();
  200. }
  201. void VNCServerST::unblockUpdates()
  202. {
  203. assert(blockCounter > 0);
  204. blockCounter--;
  205. // Restart the frame clock if we have updates
  206. if (blockCounter == 0) {
  207. if (!comparer->is_empty())
  208. startFrameClock();
  209. }
  210. }
  211. void VNCServerST::setPixelBuffer(PixelBuffer* pb_, const ScreenSet& layout)
  212. {
  213. if (comparer)
  214. comparer->logStats();
  215. pb = pb_;
  216. delete comparer;
  217. comparer = 0;
  218. if (!pb) {
  219. screenLayout = ScreenSet();
  220. if (desktopStarted)
  221. throw Exception("setPixelBuffer: null PixelBuffer when desktopStarted?");
  222. return;
  223. }
  224. if (!layout.validate(pb->width(), pb->height()))
  225. throw Exception("setPixelBuffer: invalid screen layout");
  226. screenLayout = layout;
  227. // Assume the framebuffer contents wasn't saved and reset everything
  228. // that tracks its contents
  229. comparer = new ComparingUpdateTracker(pb);
  230. renderedCursorInvalid = true;
  231. add_changed(pb->getRect());
  232. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  233. for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
  234. ci_next = ci; ci_next++;
  235. (*ci)->pixelBufferChange();
  236. // Since the new pixel buffer means an ExtendedDesktopSize needs to
  237. // be sent anyway, we don't need to call screenLayoutChange.
  238. }
  239. }
  240. void VNCServerST::setPixelBuffer(PixelBuffer* pb_)
  241. {
  242. ScreenSet layout = screenLayout;
  243. // Check that the screen layout is still valid
  244. if (pb_ && !layout.validate(pb_->width(), pb_->height())) {
  245. Rect fbRect;
  246. ScreenSet::iterator iter, iter_next;
  247. fbRect.setXYWH(0, 0, pb_->width(), pb_->height());
  248. for (iter = layout.begin();iter != layout.end();iter = iter_next) {
  249. iter_next = iter; ++iter_next;
  250. if (iter->dimensions.enclosed_by(fbRect))
  251. continue;
  252. iter->dimensions = iter->dimensions.intersect(fbRect);
  253. if (iter->dimensions.is_empty()) {
  254. slog.info("Removing screen %d (%x) as it is completely outside the new framebuffer",
  255. (int)iter->id, (unsigned)iter->id);
  256. layout.remove_screen(iter->id);
  257. }
  258. }
  259. }
  260. // Make sure that we have at least one screen
  261. if (layout.num_screens() == 0)
  262. layout.add_screen(Screen(0, 0, 0, pb_->width(), pb_->height(), 0));
  263. setPixelBuffer(pb_, layout);
  264. }
  265. void VNCServerST::setScreenLayout(const ScreenSet& layout)
  266. {
  267. if (!pb)
  268. throw Exception("setScreenLayout: new screen layout without a PixelBuffer");
  269. if (!layout.validate(pb->width(), pb->height()))
  270. throw Exception("setScreenLayout: invalid screen layout");
  271. screenLayout = layout;
  272. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  273. for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
  274. ci_next = ci; ci_next++;
  275. (*ci)->screenLayoutChangeOrClose(reasonServer);
  276. }
  277. }
  278. void VNCServerST::requestClipboard()
  279. {
  280. if (clipboardClient == NULL) {
  281. slog.debug("Got request for client clipboard but no client currently owns the clipboard");
  282. return;
  283. }
  284. clipboardClient->requestClipboardOrClose();
  285. }
  286. void VNCServerST::announceClipboard(bool available)
  287. {
  288. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  289. clipboardRequestors.clear();
  290. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  291. ci_next = ci; ci_next++;
  292. (*ci)->announceClipboardOrClose(available);
  293. }
  294. }
  295. void VNCServerST::sendClipboardData(const char* data)
  296. {
  297. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  298. if (strchr(data, '\r') != NULL)
  299. throw Exception("Invalid carriage return in clipboard data");
  300. for (ci = clipboardRequestors.begin();
  301. ci != clipboardRequestors.end(); ci = ci_next) {
  302. ci_next = ci; ci_next++;
  303. (*ci)->sendClipboardDataOrClose(data);
  304. }
  305. clipboardRequestors.clear();
  306. }
  307. void VNCServerST::bell()
  308. {
  309. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  310. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  311. ci_next = ci; ci_next++;
  312. (*ci)->bellOrClose();
  313. }
  314. }
  315. void VNCServerST::setName(const char* name_)
  316. {
  317. name.replaceBuf(strDup(name_));
  318. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  319. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  320. ci_next = ci; ci_next++;
  321. (*ci)->setDesktopNameOrClose(name_);
  322. }
  323. }
  324. void VNCServerST::add_changed(const Region& region)
  325. {
  326. if (comparer == NULL)
  327. return;
  328. comparer->add_changed(region);
  329. startFrameClock();
  330. }
  331. void VNCServerST::add_copied(const Region& dest, const Point& delta)
  332. {
  333. if (comparer == NULL)
  334. return;
  335. comparer->add_copied(dest, delta);
  336. startFrameClock();
  337. }
  338. void VNCServerST::setCursor(int width, int height, const Point& newHotspot,
  339. const rdr::U8* data)
  340. {
  341. delete cursor;
  342. cursor = new Cursor(width, height, newHotspot, data);
  343. cursor->crop();
  344. renderedCursorInvalid = true;
  345. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  346. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  347. ci_next = ci; ci_next++;
  348. (*ci)->renderedCursorChange();
  349. (*ci)->setCursorOrClose();
  350. }
  351. }
  352. void VNCServerST::setCursorPos(const Point& pos, bool warped)
  353. {
  354. if (!cursorPos.equals(pos)) {
  355. cursorPos = pos;
  356. renderedCursorInvalid = true;
  357. std::list<VNCSConnectionST*>::iterator ci;
  358. for (ci = clients.begin(); ci != clients.end(); ci++) {
  359. (*ci)->renderedCursorChange();
  360. if (warped)
  361. (*ci)->cursorPositionChange();
  362. }
  363. }
  364. }
  365. void VNCServerST::setLEDState(unsigned int state)
  366. {
  367. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  368. if (state == ledState)
  369. return;
  370. ledState = state;
  371. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  372. ci_next = ci; ci_next++;
  373. (*ci)->setLEDStateOrClose(state);
  374. }
  375. }
  376. // Event handlers
  377. void VNCServerST::keyEvent(rdr::U32 keysym, rdr::U32 keycode, bool down)
  378. {
  379. if (rfb::Server::maxIdleTime)
  380. idleTimer.start(secsToMillis(rfb::Server::maxIdleTime));
  381. // Remap the key if required
  382. if (keyRemapper) {
  383. rdr::U32 newkey;
  384. newkey = keyRemapper->remapKey(keysym);
  385. if (newkey != keysym) {
  386. slog.debug("Key remapped to 0x%x", 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. CharArray name;
  540. name.buf = client->getSock()->getPeerAddress();
  541. blHosts->clearBlackmark(name.buf);
  542. // - Prepare the desktop for that the client will start requiring
  543. // resources after this
  544. startDesktop();
  545. // - Special case to provide a more useful error message
  546. if (rfb::Server::neverShared &&
  547. !rfb::Server::disconnectClients &&
  548. authClientCount() > 0) {
  549. approveConnection(client->getSock(), false,
  550. "The server is already in use");
  551. return;
  552. }
  553. // - Are we configured to do queries?
  554. if (!rfb::Server::queryConnect &&
  555. !client->getSock()->requiresQuery()) {
  556. approveConnection(client->getSock(), true, NULL);
  557. return;
  558. }
  559. // - Does the client have the right to bypass the query?
  560. if (client->accessCheck(SConnection::AccessNoQuery))
  561. {
  562. approveConnection(client->getSock(), true, NULL);
  563. return;
  564. }
  565. desktop->queryConnection(client->getSock(), userName);
  566. }
  567. void VNCServerST::clientReady(VNCSConnectionST* client, bool shared)
  568. {
  569. if (!shared) {
  570. if (rfb::Server::disconnectClients &&
  571. client->accessCheck(SConnection::AccessNonShared)) {
  572. // - Close all the other connected clients
  573. slog.debug("non-shared connection - closing clients");
  574. closeClients("Non-shared connection requested", client->getSock());
  575. } else {
  576. // - Refuse this connection if there are existing clients, in addition to
  577. // this one
  578. if (authClientCount() > 1) {
  579. client->close("Server is already in use");
  580. return;
  581. }
  582. }
  583. }
  584. }
  585. // -=- Internal methods
  586. void VNCServerST::startDesktop()
  587. {
  588. if (!desktopStarted) {
  589. slog.debug("starting desktop");
  590. desktop->start(this);
  591. if (!pb)
  592. throw Exception("SDesktop::start() did not set a valid PixelBuffer");
  593. desktopStarted = true;
  594. // The tracker might have accumulated changes whilst we were
  595. // stopped, so flush those out
  596. if (!comparer->is_empty())
  597. writeUpdate();
  598. }
  599. }
  600. void VNCServerST::stopDesktop()
  601. {
  602. if (desktopStarted) {
  603. slog.debug("stopping desktop");
  604. desktopStarted = false;
  605. desktop->stop();
  606. stopFrameClock();
  607. }
  608. }
  609. int VNCServerST::authClientCount() {
  610. int count = 0;
  611. std::list<VNCSConnectionST*>::iterator ci;
  612. for (ci = clients.begin(); ci != clients.end(); ci++) {
  613. if ((*ci)->authenticated())
  614. count++;
  615. }
  616. return count;
  617. }
  618. inline bool VNCServerST::needRenderedCursor()
  619. {
  620. std::list<VNCSConnectionST*>::iterator ci;
  621. for (ci = clients.begin(); ci != clients.end(); ci++)
  622. if ((*ci)->needRenderedCursor()) return true;
  623. return false;
  624. }
  625. void VNCServerST::startFrameClock()
  626. {
  627. if (frameTimer.isStarted())
  628. return;
  629. if (blockCounter > 0)
  630. return;
  631. if (!desktopStarted)
  632. return;
  633. // The first iteration will be just half a frame as we get a very
  634. // unstable update rate if we happen to be perfectly in sync with
  635. // the application's update rate
  636. frameTimer.start(1000/rfb::Server::frameRate/2);
  637. }
  638. void VNCServerST::stopFrameClock()
  639. {
  640. frameTimer.stop();
  641. }
  642. int VNCServerST::msToNextUpdate()
  643. {
  644. // FIXME: If the application is updating slower than frameRate then
  645. // we could allow the clients more time here
  646. if (!frameTimer.isStarted())
  647. return 1000/rfb::Server::frameRate/2;
  648. else
  649. return frameTimer.getRemainingMs();
  650. }
  651. // writeUpdate() is called on a regular interval in order to see what
  652. // updates are pending and propagates them to the update tracker for
  653. // each client. It uses the ComparingUpdateTracker's compare() method
  654. // to filter out areas of the screen which haven't actually changed. It
  655. // also checks the state of the (server-side) rendered cursor, if
  656. // necessary rendering it again with the correct background.
  657. void VNCServerST::writeUpdate()
  658. {
  659. UpdateInfo ui;
  660. Region toCheck;
  661. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  662. assert(blockCounter == 0);
  663. assert(desktopStarted);
  664. comparer->getUpdateInfo(&ui, pb->getRect());
  665. toCheck = ui.changed.union_(ui.copied);
  666. if (needRenderedCursor()) {
  667. Rect clippedCursorRect = Rect(0, 0, cursor->width(), cursor->height())
  668. .translate(cursorPos.subtract(cursor->hotspot()))
  669. .intersect(pb->getRect());
  670. if (!toCheck.intersect(clippedCursorRect).is_empty())
  671. renderedCursorInvalid = true;
  672. }
  673. pb->grabRegion(toCheck);
  674. if (getComparerState())
  675. comparer->enable();
  676. else
  677. comparer->disable();
  678. if (comparer->compare())
  679. comparer->getUpdateInfo(&ui, pb->getRect());
  680. comparer->clear();
  681. for (ci = clients.begin(); ci != clients.end(); ci = ci_next) {
  682. ci_next = ci; ci_next++;
  683. (*ci)->add_copied(ui.copied, ui.copy_delta);
  684. (*ci)->add_changed(ui.changed);
  685. (*ci)->writeFramebufferUpdateOrClose();
  686. }
  687. }
  688. // checkUpdate() is called by clients to see if it is safe to read from
  689. // the framebuffer at this time.
  690. Region VNCServerST::getPendingRegion()
  691. {
  692. UpdateInfo ui;
  693. // Block clients as the frame buffer cannot be safely accessed
  694. if (blockCounter > 0)
  695. return pb->getRect();
  696. // Block client from updating if there are pending updates
  697. if (comparer->is_empty())
  698. return Region();
  699. comparer->getUpdateInfo(&ui, pb->getRect());
  700. return ui.changed.union_(ui.copied);
  701. }
  702. const RenderedCursor* VNCServerST::getRenderedCursor()
  703. {
  704. if (renderedCursorInvalid) {
  705. renderedCursor.update(pb, cursor, cursorPos);
  706. renderedCursorInvalid = false;
  707. }
  708. return &renderedCursor;
  709. }
  710. bool VNCServerST::getComparerState()
  711. {
  712. if (rfb::Server::compareFB == 0)
  713. return false;
  714. if (rfb::Server::compareFB != 2)
  715. return true;
  716. std::list<VNCSConnectionST*>::iterator ci, ci_next;
  717. for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
  718. ci_next = ci; ci_next++;
  719. if ((*ci)->getComparerState())
  720. return true;
  721. }
  722. return false;
  723. }