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.

VNCSConnectionST.cxx 33KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2009-2019 Pierre Ossman for Cendio AB
  3. * Copyright 2018 Peter Astrand for Cendio AB
  4. *
  5. * This is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This software is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this software; if not, write to the Free Software
  17. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  18. * USA.
  19. */
  20. #ifdef HAVE_CONFIG_H
  21. #include <config.h>
  22. #endif
  23. #include <network/TcpSocket.h>
  24. #include <rfb/ComparingUpdateTracker.h>
  25. #include <rfb/Encoder.h>
  26. #include <rfb/Exception.h>
  27. #include <rfb/KeyRemapper.h>
  28. #include <rfb/KeysymStr.h>
  29. #include <rfb/LogWriter.h>
  30. #include <rfb/Security.h>
  31. #include <rfb/ServerCore.h>
  32. #include <rfb/SMsgWriter.h>
  33. #include <rfb/VNCServerST.h>
  34. #include <rfb/VNCSConnectionST.h>
  35. #include <rfb/screenTypes.h>
  36. #include <rfb/fenceTypes.h>
  37. #include <rfb/ledStates.h>
  38. #define XK_LATIN1
  39. #define XK_MISCELLANY
  40. #define XK_XKB_KEYS
  41. #include <rfb/keysymdef.h>
  42. #include <rfb/util.h>
  43. using namespace rfb;
  44. static LogWriter vlog("VNCSConnST");
  45. static Cursor emptyCursor(0, 0, Point(0, 0), NULL);
  46. VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
  47. bool reverse)
  48. : sock(s), reverseConnection(reverse),
  49. inProcessMessages(false),
  50. pendingSyncFence(false), syncFence(false), fenceFlags(0),
  51. fenceDataLen(0), fenceData(NULL), congestionTimer(this),
  52. losslessTimer(this), server(server_),
  53. updateRenderedCursor(false), removeRenderedCursor(false),
  54. continuousUpdates(false), encodeManager(this), idleTimer(this),
  55. pointerEventTime(0), clientHasCursor(false)
  56. {
  57. setStreams(&sock->inStream(), &sock->outStream());
  58. peerEndpoint = sock->getPeerEndpoint();
  59. // Kick off the idle timer
  60. if (rfb::Server::idleTimeout) {
  61. // minimum of 15 seconds while authenticating
  62. if (rfb::Server::idleTimeout < 15)
  63. idleTimer.start(secsToMillis(15));
  64. else
  65. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  66. }
  67. }
  68. VNCSConnectionST::~VNCSConnectionST()
  69. {
  70. // If we reach here then VNCServerST is deleting us!
  71. if (!closeReason.empty())
  72. vlog.info("closing %s: %s", peerEndpoint.c_str(),
  73. closeReason.c_str());
  74. // Release any keys the client still had pressed
  75. while (!pressedKeys.empty()) {
  76. uint32_t keysym, keycode;
  77. keysym = pressedKeys.begin()->second;
  78. keycode = pressedKeys.begin()->first;
  79. pressedKeys.erase(pressedKeys.begin());
  80. vlog.debug("Releasing key 0x%04x / XK_%s (0x%04x) on client disconnect",
  81. keycode, KeySymName(keysym), keysym);
  82. server->keyEvent(keysym, keycode, false);
  83. }
  84. delete [] fenceData;
  85. }
  86. // SConnection methods
  87. bool VNCSConnectionST::accessCheck(AccessRights ar) const
  88. {
  89. // Reverse connections are user initiated, so they are implicitly
  90. // allowed to bypass the query
  91. if (reverseConnection)
  92. ar &= ~AccessNoQuery;
  93. return SConnection::accessCheck(ar);
  94. }
  95. void VNCSConnectionST::close(const char* reason)
  96. {
  97. SConnection::close(reason);
  98. // Log the reason for the close
  99. if (closeReason.empty())
  100. closeReason = reason;
  101. else
  102. vlog.debug("second close: %s (%s)", peerEndpoint.c_str(), reason);
  103. try {
  104. if (sock->outStream().hasBufferedData()) {
  105. sock->outStream().cork(false);
  106. sock->outStream().flush();
  107. if (sock->outStream().hasBufferedData())
  108. vlog.error("Failed to flush remaining socket data on close");
  109. }
  110. } catch (rdr::Exception& e) {
  111. vlog.error("Failed to flush remaining socket data on close: %s", e.str());
  112. }
  113. // Just shutdown the socket and mark our state as closing. Eventually the
  114. // calling code will call VNCServerST's removeSocket() method causing us to
  115. // be deleted.
  116. sock->shutdown();
  117. }
  118. // Methods called from VNCServerST
  119. bool VNCSConnectionST::init()
  120. {
  121. try {
  122. initialiseProtocol();
  123. } catch (rdr::Exception& e) {
  124. close(e.str());
  125. return false;
  126. }
  127. return true;
  128. }
  129. void VNCSConnectionST::processMessages()
  130. {
  131. if (state() == RFBSTATE_CLOSING) return;
  132. try {
  133. inProcessMessages = true;
  134. // Get the underlying transport to build large packets if we send
  135. // multiple small responses.
  136. getOutStream()->cork(true);
  137. while (true) {
  138. if (pendingSyncFence)
  139. syncFence = true;
  140. if (!processMsg())
  141. break;
  142. if (syncFence) {
  143. writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
  144. syncFence = false;
  145. pendingSyncFence = false;
  146. }
  147. }
  148. // Flush out everything in case we go idle after this.
  149. getOutStream()->cork(false);
  150. inProcessMessages = false;
  151. // If there were anything requiring an update, try to send it here.
  152. // We wait until now with this to aggregate responses and to give
  153. // higher priority to user actions such as keyboard and pointer events.
  154. writeFramebufferUpdate();
  155. } catch (rdr::EndOfStream&) {
  156. close("Clean disconnection");
  157. } catch (rdr::Exception &e) {
  158. close(e.str());
  159. }
  160. }
  161. void VNCSConnectionST::flushSocket()
  162. {
  163. if (state() == RFBSTATE_CLOSING) return;
  164. try {
  165. sock->outStream().flush();
  166. // Flushing the socket might release an update that was previously
  167. // delayed because of congestion.
  168. if (!sock->outStream().hasBufferedData())
  169. writeFramebufferUpdate();
  170. } catch (rdr::Exception &e) {
  171. close(e.str());
  172. }
  173. }
  174. void VNCSConnectionST::pixelBufferChange()
  175. {
  176. try {
  177. if (!authenticated()) return;
  178. if (client.width() && client.height() &&
  179. (server->getPixelBuffer()->width() != client.width() ||
  180. server->getPixelBuffer()->height() != client.height()))
  181. {
  182. // We need to clip the next update to the new size, but also add any
  183. // extra bits if it's bigger. If we wanted to do this exactly, something
  184. // like the code below would do it, but at the moment we just update the
  185. // entire new size. However, we do need to clip the damagedCursorRegion
  186. // because that might be added to updates in writeFramebufferUpdate().
  187. //updates.intersect(server->pb->getRect());
  188. //
  189. //if (server->pb->width() > client.width())
  190. // updates.add_changed(Rect(client.width(), 0, server->pb->width(),
  191. // server->pb->height()));
  192. //if (server->pb->height() > client.height())
  193. // updates.add_changed(Rect(0, client.height(), client.width(),
  194. // server->pb->height()));
  195. damagedCursorRegion.assign_intersect(server->getPixelBuffer()->getRect());
  196. client.setDimensions(server->getPixelBuffer()->width(),
  197. server->getPixelBuffer()->height(),
  198. server->getScreenLayout());
  199. if (state() == RFBSTATE_NORMAL) {
  200. if (!client.supportsDesktopSize()) {
  201. close("Client does not support desktop resize");
  202. return;
  203. }
  204. writer()->writeDesktopSize(reasonServer);
  205. }
  206. // Drop any lossy tracking that is now outside the framebuffer
  207. encodeManager.pruneLosslessRefresh(Region(server->getPixelBuffer()->getRect()));
  208. }
  209. // Just update the whole screen at the moment because we're too lazy to
  210. // work out what's actually changed.
  211. updates.clear();
  212. updates.add_changed(server->getPixelBuffer()->getRect());
  213. writeFramebufferUpdate();
  214. } catch(rdr::Exception &e) {
  215. close(e.str());
  216. }
  217. }
  218. void VNCSConnectionST::writeFramebufferUpdateOrClose()
  219. {
  220. try {
  221. writeFramebufferUpdate();
  222. } catch(rdr::Exception &e) {
  223. close(e.str());
  224. }
  225. }
  226. void VNCSConnectionST::screenLayoutChangeOrClose(uint16_t reason)
  227. {
  228. try {
  229. screenLayoutChange(reason);
  230. writeFramebufferUpdate();
  231. } catch(rdr::Exception &e) {
  232. close(e.str());
  233. }
  234. }
  235. void VNCSConnectionST::bellOrClose()
  236. {
  237. try {
  238. if (state() == RFBSTATE_NORMAL) writer()->writeBell();
  239. } catch(rdr::Exception& e) {
  240. close(e.str());
  241. }
  242. }
  243. void VNCSConnectionST::setDesktopNameOrClose(const char *name)
  244. {
  245. try {
  246. setDesktopName(name);
  247. writeFramebufferUpdate();
  248. } catch(rdr::Exception& e) {
  249. close(e.str());
  250. }
  251. }
  252. void VNCSConnectionST::setCursorOrClose()
  253. {
  254. try {
  255. setCursor();
  256. writeFramebufferUpdate();
  257. } catch(rdr::Exception& e) {
  258. close(e.str());
  259. }
  260. }
  261. void VNCSConnectionST::setLEDStateOrClose(unsigned int state)
  262. {
  263. try {
  264. setLEDState(state);
  265. writeFramebufferUpdate();
  266. } catch(rdr::Exception& e) {
  267. close(e.str());
  268. }
  269. }
  270. void VNCSConnectionST::requestClipboardOrClose()
  271. {
  272. try {
  273. if (state() != RFBSTATE_NORMAL) return;
  274. if (!accessCheck(AccessCutText)) return;
  275. if (!rfb::Server::acceptCutText) return;
  276. requestClipboard();
  277. } catch(rdr::Exception& e) {
  278. close(e.str());
  279. }
  280. }
  281. void VNCSConnectionST::announceClipboardOrClose(bool available)
  282. {
  283. try {
  284. if (state() != RFBSTATE_NORMAL) return;
  285. if (!accessCheck(AccessCutText)) return;
  286. if (!rfb::Server::sendCutText) return;
  287. announceClipboard(available);
  288. } catch(rdr::Exception& e) {
  289. close(e.str());
  290. }
  291. }
  292. void VNCSConnectionST::sendClipboardDataOrClose(const char* data)
  293. {
  294. try {
  295. if (state() != RFBSTATE_NORMAL) return;
  296. if (!accessCheck(AccessCutText)) return;
  297. if (!rfb::Server::sendCutText) return;
  298. sendClipboardData(data);
  299. } catch(rdr::Exception& e) {
  300. close(e.str());
  301. }
  302. }
  303. bool VNCSConnectionST::getComparerState()
  304. {
  305. // We interpret a low compression level as an indication that the client
  306. // wants to prioritise CPU usage over bandwidth, and hence disable the
  307. // comparing update tracker.
  308. return (client.compressLevel == -1) || (client.compressLevel > 1);
  309. }
  310. // renderedCursorChange() is called whenever the server-side rendered cursor
  311. // changes shape or position. It ensures that the next update will clean up
  312. // the old rendered cursor and if necessary draw the new rendered cursor.
  313. void VNCSConnectionST::renderedCursorChange()
  314. {
  315. if (state() != RFBSTATE_NORMAL) return;
  316. // Are we switching between client-side and server-side cursor?
  317. if (clientHasCursor == needRenderedCursor())
  318. setCursorOrClose();
  319. bool hasRenderedCursor = !damagedCursorRegion.is_empty();
  320. if (hasRenderedCursor)
  321. removeRenderedCursor = true;
  322. if (needRenderedCursor()) {
  323. updateRenderedCursor = true;
  324. writeFramebufferUpdateOrClose();
  325. }
  326. }
  327. // cursorPositionChange() is called whenever the cursor has changed position by
  328. // the server. If the client supports being informed about these changes then
  329. // it will arrange for the new cursor position to be sent to the client.
  330. void VNCSConnectionST::cursorPositionChange()
  331. {
  332. setCursorPos();
  333. }
  334. // needRenderedCursor() returns true if this client needs the server-side
  335. // rendered cursor. This may be because it does not support local cursor or
  336. // because the current cursor position has not been set by this client.
  337. // Unfortunately we can't know for sure when the current cursor position has
  338. // been set by this client. We guess that this is the case when the current
  339. // cursor position is the same as the last pointer event from this client, or
  340. // if it is a very short time since this client's last pointer event (up to a
  341. // second). [ Ideally we should do finer-grained timing here and make the time
  342. // configurable, but I don't think it's that important. ]
  343. bool VNCSConnectionST::needRenderedCursor()
  344. {
  345. if (state() != RFBSTATE_NORMAL)
  346. return false;
  347. if (!client.supportsLocalCursor())
  348. return true;
  349. if ((server->getCursorPos() != pointerEventPos) &&
  350. (time(0) - pointerEventTime) > 0)
  351. return true;
  352. return false;
  353. }
  354. void VNCSConnectionST::approveConnectionOrClose(bool accept,
  355. const char* reason)
  356. {
  357. try {
  358. approveConnection(accept, reason);
  359. } catch (rdr::Exception& e) {
  360. close(e.str());
  361. }
  362. }
  363. // -=- Callbacks from SConnection
  364. void VNCSConnectionST::authSuccess()
  365. {
  366. if (rfb::Server::idleTimeout)
  367. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  368. // - Set the connection parameters appropriately
  369. client.setDimensions(server->getPixelBuffer()->width(),
  370. server->getPixelBuffer()->height(),
  371. server->getScreenLayout());
  372. client.setName(server->getName());
  373. client.setLEDState(server->getLEDState());
  374. // - Set the default pixel format
  375. client.setPF(server->getPixelBuffer()->getPF());
  376. char buffer[256];
  377. client.pf().print(buffer, 256);
  378. vlog.info("Server default pixel format %s", buffer);
  379. // - Mark the entire display as "dirty"
  380. updates.add_changed(server->getPixelBuffer()->getRect());
  381. }
  382. void VNCSConnectionST::queryConnection(const char* userName)
  383. {
  384. server->queryConnection(this, userName);
  385. }
  386. void VNCSConnectionST::clientInit(bool shared)
  387. {
  388. if (rfb::Server::idleTimeout)
  389. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  390. if (rfb::Server::alwaysShared || reverseConnection) shared = true;
  391. if (!accessCheck(AccessNonShared)) shared = true;
  392. if (rfb::Server::neverShared) shared = false;
  393. SConnection::clientInit(shared);
  394. server->clientReady(this, shared);
  395. }
  396. void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
  397. {
  398. SConnection::setPixelFormat(pf);
  399. char buffer[256];
  400. pf.print(buffer, 256);
  401. vlog.info("Client pixel format %s", buffer);
  402. setCursor();
  403. }
  404. void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
  405. {
  406. if (rfb::Server::idleTimeout)
  407. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  408. pointerEventTime = time(0);
  409. if (!accessCheck(AccessPtrEvents)) return;
  410. if (!rfb::Server::acceptPointerEvents) return;
  411. pointerEventPos = pos;
  412. server->pointerEvent(this, pointerEventPos, buttonMask);
  413. }
  414. class VNCSConnectionSTShiftPresser {
  415. public:
  416. VNCSConnectionSTShiftPresser(VNCServerST* server_)
  417. : server(server_), pressed(false) {}
  418. ~VNCSConnectionSTShiftPresser() {
  419. if (pressed) {
  420. vlog.debug("Releasing fake Shift_L");
  421. server->keyEvent(XK_Shift_L, 0, false);
  422. }
  423. }
  424. void press() {
  425. vlog.debug("Pressing fake Shift_L");
  426. server->keyEvent(XK_Shift_L, 0, true);
  427. pressed = true;
  428. }
  429. VNCServerST* server;
  430. bool pressed;
  431. };
  432. // keyEvent() - record in the pressedKeys which keys were pressed. Allow
  433. // multiple down events (for autorepeat), but only allow a single up event.
  434. void VNCSConnectionST::keyEvent(uint32_t keysym, uint32_t keycode, bool down) {
  435. uint32_t lookup;
  436. if (rfb::Server::idleTimeout)
  437. idleTimer.start(secsToMillis(rfb::Server::idleTimeout));
  438. if (!accessCheck(AccessKeyEvents)) return;
  439. if (!rfb::Server::acceptKeyEvents) return;
  440. if (down)
  441. vlog.debug("Key pressed: 0x%04x / XK_%s (0x%04x)",
  442. keycode, KeySymName(keysym), keysym);
  443. else
  444. vlog.debug("Key released: 0x%04x / XK_%s (0x%04x)",
  445. keycode, KeySymName(keysym), keysym);
  446. // Avoid lock keys if we don't know the server state
  447. if ((server->getLEDState() == ledUnknown) &&
  448. ((keysym == XK_Caps_Lock) ||
  449. (keysym == XK_Num_Lock))) {
  450. vlog.debug("Ignoring lock key (e.g. caps lock)");
  451. return;
  452. }
  453. // Lock key heuristics
  454. // (only for clients that do not support the LED state extension)
  455. if (!client.supportsLEDState()) {
  456. if (down && (server->getLEDState() != ledUnknown)) {
  457. // CapsLock synchronisation heuristic
  458. // (this assumes standard interaction between CapsLock the Shift
  459. // keys and normal characters)
  460. if (((keysym >= XK_A) && (keysym <= XK_Z)) ||
  461. ((keysym >= XK_a) && (keysym <= XK_z))) {
  462. bool uppercase, shift, lock;
  463. uppercase = (keysym >= XK_A) && (keysym <= XK_Z);
  464. shift = isShiftPressed();
  465. lock = server->getLEDState() & ledCapsLock;
  466. if (lock == (uppercase == shift)) {
  467. vlog.debug("Inserting fake CapsLock to get in sync with client");
  468. server->keyEvent(XK_Caps_Lock, 0, true);
  469. server->keyEvent(XK_Caps_Lock, 0, false);
  470. }
  471. }
  472. // NumLock synchronisation heuristic
  473. // (this is more cautious because of the differences between Unix,
  474. // Windows and macOS)
  475. if (((keysym >= XK_KP_Home) && (keysym <= XK_KP_Delete)) ||
  476. ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
  477. (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal)) {
  478. bool number, shift, lock;
  479. number = ((keysym >= XK_KP_0) && (keysym <= XK_KP_9)) ||
  480. (keysym == XK_KP_Separator) || (keysym == XK_KP_Decimal);
  481. shift = isShiftPressed();
  482. lock = server->getLEDState() & ledNumLock;
  483. if (shift) {
  484. // We don't know the appropriate NumLock state for when Shift
  485. // is pressed as it could be one of:
  486. //
  487. // a) A Unix client where Shift negates NumLock
  488. //
  489. // b) A Windows client where Shift only cancels NumLock
  490. //
  491. // c) A macOS client where Shift doesn't have any effect
  492. //
  493. } else if (lock == (number == shift)) {
  494. vlog.debug("Inserting fake NumLock to get in sync with client");
  495. server->keyEvent(XK_Num_Lock, 0, true);
  496. server->keyEvent(XK_Num_Lock, 0, false);
  497. }
  498. }
  499. }
  500. }
  501. // Turn ISO_Left_Tab into shifted Tab.
  502. VNCSConnectionSTShiftPresser shiftPresser(server);
  503. if (keysym == XK_ISO_Left_Tab) {
  504. if (!isShiftPressed())
  505. shiftPresser.press();
  506. keysym = XK_Tab;
  507. }
  508. // We need to be able to track keys, so generate a fake index when we
  509. // aren't given a keycode
  510. if (keycode == 0)
  511. lookup = 0x80000000 | keysym;
  512. else
  513. lookup = keycode;
  514. // We force the same keysym for an already down key for the
  515. // sake of sanity
  516. if (pressedKeys.find(lookup) != pressedKeys.end())
  517. keysym = pressedKeys[lookup];
  518. if (down) {
  519. pressedKeys[lookup] = keysym;
  520. } else {
  521. if (!pressedKeys.erase(lookup))
  522. return;
  523. }
  524. server->keyEvent(keysym, keycode, down);
  525. }
  526. void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
  527. {
  528. Rect safeRect;
  529. if (!accessCheck(AccessView)) return;
  530. SConnection::framebufferUpdateRequest(r, incremental);
  531. // Check that the client isn't sending crappy requests
  532. if (!r.enclosed_by(Rect(0, 0, client.width(), client.height()))) {
  533. vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
  534. r.width(), r.height(), r.tl.x, r.tl.y,
  535. client.width(), client.height());
  536. safeRect = r.intersect(Rect(0, 0, client.width(), client.height()));
  537. } else {
  538. safeRect = r;
  539. }
  540. // Just update the requested region.
  541. // Framebuffer update will be sent a bit later, see processMessages().
  542. Region reqRgn(safeRect);
  543. if (!incremental || !continuousUpdates)
  544. requested.assign_union(reqRgn);
  545. if (!incremental) {
  546. // Non-incremental update - treat as if area requested has changed
  547. updates.add_changed(reqRgn);
  548. // And send the screen layout to the client (which, unlike the
  549. // framebuffer dimensions, the client doesn't get during init)
  550. if (client.supportsEncoding(pseudoEncodingExtendedDesktopSize))
  551. writer()->writeDesktopSize(reasonServer);
  552. // We do not send a DesktopSize since it only contains the
  553. // framebuffer size (which the client already should know) and
  554. // because some clients don't handle extra DesktopSize events
  555. // very well.
  556. }
  557. }
  558. void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
  559. const ScreenSet& layout)
  560. {
  561. unsigned int result;
  562. char buffer[2048];
  563. vlog.debug("Got request for framebuffer resize to %dx%d",
  564. fb_width, fb_height);
  565. layout.print(buffer, sizeof(buffer));
  566. vlog.debug("%s", buffer);
  567. if (!accessCheck(AccessSetDesktopSize) ||
  568. !rfb::Server::acceptSetDesktopSize) {
  569. vlog.debug("Rejecting unauthorized framebuffer resize request");
  570. result = resultProhibited;
  571. } else {
  572. result = server->setDesktopSize(this, fb_width, fb_height, layout);
  573. }
  574. writer()->writeDesktopSize(reasonClient, result);
  575. }
  576. void VNCSConnectionST::fence(uint32_t flags, unsigned len, const uint8_t data[])
  577. {
  578. uint8_t type;
  579. if (flags & fenceFlagRequest) {
  580. if (flags & fenceFlagSyncNext) {
  581. pendingSyncFence = true;
  582. fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
  583. fenceDataLen = len;
  584. delete [] fenceData;
  585. fenceData = NULL;
  586. if (len > 0) {
  587. fenceData = new uint8_t[len];
  588. memcpy(fenceData, data, len);
  589. }
  590. return;
  591. }
  592. // We handle everything synchronously so we trivially honor these modes
  593. flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
  594. writer()->writeFence(flags, len, data);
  595. return;
  596. }
  597. if (len < 1)
  598. vlog.error("Fence response of unexpected size received");
  599. type = data[0];
  600. switch (type) {
  601. case 0:
  602. // Initial dummy fence;
  603. break;
  604. case 1:
  605. congestion.gotPong();
  606. break;
  607. default:
  608. vlog.error("Fence response of unexpected type received");
  609. }
  610. }
  611. void VNCSConnectionST::enableContinuousUpdates(bool enable,
  612. int x, int y, int w, int h)
  613. {
  614. Rect rect;
  615. if (!client.supportsFence() || !client.supportsContinuousUpdates())
  616. throw Exception("Client tried to enable continuous updates when not allowed");
  617. continuousUpdates = enable;
  618. rect.setXYWH(x, y, w, h);
  619. cuRegion.reset(rect);
  620. if (enable) {
  621. requested.clear();
  622. } else {
  623. writer()->writeEndOfContinuousUpdates();
  624. }
  625. }
  626. void VNCSConnectionST::handleClipboardRequest()
  627. {
  628. if (!accessCheck(AccessCutText)) return;
  629. server->handleClipboardRequest(this);
  630. }
  631. void VNCSConnectionST::handleClipboardAnnounce(bool available)
  632. {
  633. if (!accessCheck(AccessCutText)) return;
  634. if (!rfb::Server::acceptCutText) return;
  635. server->handleClipboardAnnounce(this, available);
  636. }
  637. void VNCSConnectionST::handleClipboardData(const char* data)
  638. {
  639. if (!accessCheck(AccessCutText)) return;
  640. if (!rfb::Server::acceptCutText) return;
  641. server->handleClipboardData(this, data);
  642. }
  643. // supportsLocalCursor() is called whenever the status of
  644. // client.supportsLocalCursor() has changed. If the client does now support local
  645. // cursor, we make sure that the old server-side rendered cursor is cleaned up
  646. // and the cursor is sent to the client.
  647. void VNCSConnectionST::supportsLocalCursor()
  648. {
  649. bool hasRenderedCursor = !damagedCursorRegion.is_empty();
  650. if (hasRenderedCursor && !needRenderedCursor())
  651. removeRenderedCursor = true;
  652. setCursor();
  653. }
  654. void VNCSConnectionST::supportsFence()
  655. {
  656. uint8_t type = 0;
  657. writer()->writeFence(fenceFlagRequest, sizeof(type), &type);
  658. }
  659. void VNCSConnectionST::supportsContinuousUpdates()
  660. {
  661. // We refuse to use continuous updates if we cannot monitor the buffer
  662. // usage using fences.
  663. if (!client.supportsFence())
  664. return;
  665. writer()->writeEndOfContinuousUpdates();
  666. }
  667. void VNCSConnectionST::supportsLEDState()
  668. {
  669. if (client.ledState() == ledUnknown)
  670. return;
  671. writer()->writeLEDState();
  672. }
  673. bool VNCSConnectionST::handleTimeout(Timer* t)
  674. {
  675. try {
  676. if ((t == &congestionTimer) ||
  677. (t == &losslessTimer))
  678. writeFramebufferUpdate();
  679. } catch (rdr::Exception& e) {
  680. close(e.str());
  681. }
  682. if (t == &idleTimer)
  683. close("Idle timeout");
  684. return false;
  685. }
  686. bool VNCSConnectionST::isShiftPressed()
  687. {
  688. std::map<uint32_t, uint32_t>::const_iterator iter;
  689. for (iter = pressedKeys.begin(); iter != pressedKeys.end(); ++iter) {
  690. if (iter->second == XK_Shift_L)
  691. return true;
  692. if (iter->second == XK_Shift_R)
  693. return true;
  694. }
  695. return false;
  696. }
  697. void VNCSConnectionST::writeRTTPing()
  698. {
  699. uint8_t type;
  700. if (!client.supportsFence())
  701. return;
  702. congestion.updatePosition(sock->outStream().length());
  703. // We need to make sure any old update are already processed by the
  704. // time we get the response back. This allows us to reliably throttle
  705. // back on client overload, as well as network overload.
  706. type = 1;
  707. writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
  708. sizeof(type), &type);
  709. congestion.sentPing();
  710. }
  711. bool VNCSConnectionST::isCongested()
  712. {
  713. int eta;
  714. congestionTimer.stop();
  715. // Stuff still waiting in the send buffer?
  716. sock->outStream().flush();
  717. congestion.debugTrace("congestion-trace.csv", sock->getFd());
  718. if (sock->outStream().hasBufferedData())
  719. return true;
  720. if (!client.supportsFence())
  721. return false;
  722. congestion.updatePosition(sock->outStream().length());
  723. if (!congestion.isCongested())
  724. return false;
  725. eta = congestion.getUncongestedETA();
  726. if (eta >= 0)
  727. congestionTimer.start(eta);
  728. return true;
  729. }
  730. void VNCSConnectionST::writeFramebufferUpdate()
  731. {
  732. congestion.updatePosition(sock->outStream().length());
  733. // We're in the middle of processing a command that's supposed to be
  734. // synchronised. Allowing an update to slip out right now might violate
  735. // that synchronisation.
  736. if (syncFence)
  737. return;
  738. // We try to aggregate responses, so don't send out anything whilst we
  739. // still have incoming messages. processMessages() will give us another
  740. // chance to run once things are idle.
  741. if (inProcessMessages)
  742. return;
  743. if (state() != RFBSTATE_NORMAL)
  744. return;
  745. if (requested.is_empty() && !continuousUpdates)
  746. return;
  747. // Check that we actually have some space on the link and retry in a
  748. // bit if things are congested.
  749. if (isCongested())
  750. return;
  751. // Updates often consists of many small writes, and in continuous
  752. // mode, we will also have small fence messages around the update. We
  753. // need to aggregate these in order to not clog up TCP's congestion
  754. // window.
  755. getOutStream()->cork(true);
  756. // First take care of any updates that cannot contain framebuffer data
  757. // changes.
  758. writeNoDataUpdate();
  759. // Then real data (if possible)
  760. writeDataUpdate();
  761. getOutStream()->cork(false);
  762. congestion.updatePosition(sock->outStream().length());
  763. }
  764. void VNCSConnectionST::writeNoDataUpdate()
  765. {
  766. if (!writer()->needNoDataUpdate())
  767. return;
  768. writer()->writeNoDataUpdate();
  769. // Make sure no data update is sent until next request
  770. requested.clear();
  771. }
  772. void VNCSConnectionST::writeDataUpdate()
  773. {
  774. Region req;
  775. UpdateInfo ui;
  776. bool needNewUpdateInfo;
  777. const RenderedCursor *cursor;
  778. // See what the client has requested (if anything)
  779. if (continuousUpdates)
  780. req = cuRegion.union_(requested);
  781. else
  782. req = requested;
  783. if (req.is_empty())
  784. return;
  785. // Get the lists of updates. Prior to exporting the data to the `ui' object,
  786. // getUpdateInfo() will normalize the `updates' object such way that its
  787. // `changed' and `copied' regions would not intersect.
  788. updates.getUpdateInfo(&ui, req);
  789. needNewUpdateInfo = false;
  790. // If the previous position of the rendered cursor overlaps the source of the
  791. // copy, then when the copy happens the corresponding rectangle in the
  792. // destination will be wrong, so add it to the changed region.
  793. if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) {
  794. Region bogusCopiedCursor;
  795. bogusCopiedCursor = damagedCursorRegion;
  796. bogusCopiedCursor.translate(ui.copy_delta);
  797. bogusCopiedCursor.assign_intersect(server->getPixelBuffer()->getRect());
  798. if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
  799. updates.add_changed(bogusCopiedCursor);
  800. needNewUpdateInfo = true;
  801. }
  802. }
  803. // If we need to remove the old rendered cursor, just add the region to
  804. // the changed region.
  805. if (removeRenderedCursor) {
  806. updates.add_changed(damagedCursorRegion);
  807. needNewUpdateInfo = true;
  808. damagedCursorRegion.clear();
  809. removeRenderedCursor = false;
  810. }
  811. // If we need a full cursor update then make sure its entire region
  812. // is marked as changed.
  813. if (updateRenderedCursor) {
  814. updates.add_changed(server->getRenderedCursor()->getEffectiveRect());
  815. needNewUpdateInfo = true;
  816. updateRenderedCursor = false;
  817. }
  818. // The `updates' object could change, make sure we have valid update info.
  819. if (needNewUpdateInfo)
  820. updates.getUpdateInfo(&ui, req);
  821. // If there are queued updates then we cannot safely send an update
  822. // without risking a partially updated screen
  823. if (!server->getPendingRegion().is_empty()) {
  824. req.clear();
  825. ui.changed.clear();
  826. ui.copied.clear();
  827. }
  828. // Does the client need a server-side rendered cursor?
  829. cursor = NULL;
  830. if (needRenderedCursor()) {
  831. Rect renderedCursorRect;
  832. cursor = server->getRenderedCursor();
  833. renderedCursorRect = cursor->getEffectiveRect();
  834. // Check that we don't try to copy over the cursor area, and
  835. // if that happens we need to treat it as changed so that we can
  836. // re-render it
  837. if (!ui.copied.intersect(renderedCursorRect).is_empty()) {
  838. ui.changed.assign_union(ui.copied.intersect(renderedCursorRect));
  839. ui.copied.assign_subtract(renderedCursorRect);
  840. }
  841. // Track where we've rendered the cursor
  842. damagedCursorRegion.assign_union(ui.changed.intersect(renderedCursorRect));
  843. }
  844. // If we don't have a normal update, then try a lossless refresh
  845. if (ui.is_empty() && !writer()->needFakeUpdate()) {
  846. writeLosslessRefresh();
  847. return;
  848. }
  849. // We have something to send, so let's get to it
  850. writeRTTPing();
  851. encodeManager.writeUpdate(ui, server->getPixelBuffer(), cursor);
  852. writeRTTPing();
  853. // The request might be for just part of the screen, so we cannot
  854. // just clear the entire update tracker.
  855. updates.subtract(req);
  856. requested.clear();
  857. }
  858. void VNCSConnectionST::writeLosslessRefresh()
  859. {
  860. Region req, pending;
  861. const RenderedCursor *cursor;
  862. int nextRefresh, nextUpdate;
  863. size_t bandwidth, maxUpdateSize;
  864. if (continuousUpdates)
  865. req = cuRegion.union_(requested);
  866. else
  867. req = requested;
  868. // If there are queued updates then we could not safely send an
  869. // update without risking a partially updated screen, however we
  870. // might still be able to send a lossless refresh
  871. pending = server->getPendingRegion();
  872. if (!pending.is_empty()) {
  873. UpdateInfo ui;
  874. // Don't touch the updates pending in the server core
  875. req.assign_subtract(pending);
  876. // Or any updates pending just for this connection
  877. updates.getUpdateInfo(&ui, req);
  878. req.assign_subtract(ui.changed);
  879. req.assign_subtract(ui.copied);
  880. }
  881. // Any lossy area we can refresh?
  882. if (!encodeManager.needsLosslessRefresh(req))
  883. return;
  884. // Right away? Or later?
  885. nextRefresh = encodeManager.getNextLosslessRefresh(req);
  886. if (nextRefresh > 0) {
  887. losslessTimer.start(nextRefresh);
  888. return;
  889. }
  890. // Prepare the cursor in case it overlaps with a region getting
  891. // refreshed
  892. cursor = NULL;
  893. if (needRenderedCursor())
  894. cursor = server->getRenderedCursor();
  895. // FIXME: If continuous updates aren't used then the client might
  896. // be slower than frameRate in its requests and we could
  897. // afford a larger update size
  898. nextUpdate = server->msToNextUpdate();
  899. // Don't bother if we're about to send a real update
  900. if (nextUpdate == 0)
  901. return;
  902. // FIXME: Bandwidth estimation without congestion control
  903. bandwidth = congestion.getBandwidth();
  904. // FIXME: Hard coded value for maximum CPU throughput
  905. if (bandwidth > 5000000)
  906. bandwidth = 5000000;
  907. maxUpdateSize = bandwidth * nextUpdate / 1000;
  908. writeRTTPing();
  909. encodeManager.writeLosslessRefresh(req, server->getPixelBuffer(),
  910. cursor, maxUpdateSize);
  911. writeRTTPing();
  912. requested.clear();
  913. }
  914. void VNCSConnectionST::screenLayoutChange(uint16_t reason)
  915. {
  916. if (!authenticated())
  917. return;
  918. client.setDimensions(client.width(), client.height(),
  919. server->getScreenLayout());
  920. if (state() != RFBSTATE_NORMAL)
  921. return;
  922. writer()->writeDesktopSize(reason);
  923. }
  924. // setCursor() is called whenever the cursor has changed shape or pixel format.
  925. // If the client supports local cursor then it will arrange for the cursor to
  926. // be sent to the client.
  927. void VNCSConnectionST::setCursor()
  928. {
  929. if (state() != RFBSTATE_NORMAL)
  930. return;
  931. // We need to blank out the client's cursor or there will be two
  932. if (needRenderedCursor()) {
  933. client.setCursor(emptyCursor);
  934. clientHasCursor = false;
  935. } else {
  936. client.setCursor(*server->getCursor());
  937. clientHasCursor = true;
  938. }
  939. if (client.supportsLocalCursor())
  940. writer()->writeCursor();
  941. }
  942. // setCursorPos() is called whenever the cursor has changed position by the
  943. // server. If the client supports being informed about these changes then it
  944. // will arrange for the new cursor position to be sent to the client.
  945. void VNCSConnectionST::setCursorPos()
  946. {
  947. if (state() != RFBSTATE_NORMAL)
  948. return;
  949. if (client.supportsCursorPosition()) {
  950. client.setCursorPos(server->getCursorPos());
  951. writer()->writeCursorPos();
  952. }
  953. }
  954. void VNCSConnectionST::setDesktopName(const char *name)
  955. {
  956. client.setName(name);
  957. if (state() != RFBSTATE_NORMAL)
  958. return;
  959. if (client.supportsEncoding(pseudoEncodingDesktopName))
  960. writer()->writeSetDesktopName();
  961. }
  962. void VNCSConnectionST::setLEDState(unsigned int ledstate)
  963. {
  964. if (state() != RFBSTATE_NORMAL)
  965. return;
  966. client.setLEDState(ledstate);
  967. if (client.supportsLEDState())
  968. writer()->writeLEDState();
  969. }