Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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/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. return resultProhibited;
  444. // Don't bother the desktop with an invalid configuration
  445. if (!layout.validate(fb_width, fb_height))
  446. return resultInvalid;
  447. // FIXME: the desktop will call back to VNCServerST and an extra set
  448. // of ExtendedDesktopSize messages will be sent. This is okay
  449. // protocol-wise, but unnecessary.
  450. result = desktop->setScreenLayout(fb_width, fb_height, layout);
  451. if (result != resultSuccess)
  452. return result;
  453. // Sanity check
  454. if (screenLayout != layout)
  455. throw Exception("Desktop configured a different screen layout than requested");
  456. // Notify other clients
  457. for (ci=clients.begin();ci!=clients.end();ci=ci_next) {
  458. ci_next = ci; ci_next++;
  459. if ((*ci) == requester)
  460. continue;
  461. (*ci)->screenLayoutChangeOrClose(reasonOtherClient);
  462. }
  463. return resultSuccess;
  464. }
  465. // Other public methods
  466. void VNCServerST::approveConnection(network::Socket* sock, bool accept,
  467. const char* reason)
  468. {
  469. std::list<VNCSConnectionST*>::iterator ci;
  470. for (ci = clients.begin(); ci != clients.end(); ci++) {
  471. if ((*ci)->getSock() == sock) {
  472. (*ci)->approveConnectionOrClose(accept, reason);
  473. return;
  474. }
  475. }
  476. }
  477. void VNCServerST::closeClients(const char* reason, network::Socket* except)
  478. {
  479. std::list<VNCSConnectionST*>::iterator i, next_i;
  480. for (i=clients.begin(); i!=clients.end(); i=next_i) {
  481. next_i = i; next_i++;
  482. if ((*i)->getSock() != except)
  483. (*i)->close(reason);
  484. }
  485. }
  486. void VNCServerST::getSockets(std::list<network::Socket*>* sockets)
  487. {
  488. sockets->clear();
  489. std::list<VNCSConnectionST*>::iterator ci;
  490. for (ci = clients.begin(); ci != clients.end(); ci++) {
  491. sockets->push_back((*ci)->getSock());
  492. }
  493. std::list<network::Socket*>::iterator si;
  494. for (si = closingSockets.begin(); si != closingSockets.end(); si++) {
  495. sockets->push_back(*si);
  496. }
  497. }
  498. SConnection* VNCServerST::getConnection(network::Socket* sock) {
  499. std::list<VNCSConnectionST*>::iterator ci;
  500. for (ci = clients.begin(); ci != clients.end(); ci++) {
  501. if ((*ci)->getSock() == sock)
  502. return (SConnection*)*ci;
  503. }
  504. return 0;
  505. }
  506. bool VNCServerST::handleTimeout(Timer* t)
  507. {
  508. if (t == &frameTimer) {
  509. // We keep running until we go a full interval without any updates
  510. if (comparer->is_empty())
  511. return false;
  512. writeUpdate();
  513. // If this is the first iteration then we need to adjust the timeout
  514. if (frameTimer.getTimeoutMs() != 1000/rfb::Server::frameRate) {
  515. frameTimer.start(1000/rfb::Server::frameRate);
  516. return false;
  517. }
  518. return true;
  519. } else if (t == &idleTimer) {
  520. slog.info("MaxIdleTime reached, exiting");
  521. desktop->terminate();
  522. } else if (t == &disconnectTimer) {
  523. slog.info("MaxDisconnectionTime reached, exiting");
  524. desktop->terminate();
  525. } else if (t == &connectTimer) {
  526. slog.info("MaxConnectionTime reached, exiting");
  527. desktop->terminate();
  528. }
  529. return false;
  530. }
  531. void VNCServerST::queryConnection(VNCSConnectionST* client,
  532. const char* userName)
  533. {
  534. // - Authentication succeeded - clear from blacklist
  535. CharArray name;
  536. name.buf = client->getSock()->getPeerAddress();
  537. blHosts->clearBlackmark(name.buf);
  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. }