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

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