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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. /* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
  2. * Copyright 2009-2011 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. // Debug output on what the congestion control is up to
  20. #undef CONGESTION_DEBUG
  21. #include <sys/time.h>
  22. #ifdef CONGESTION_DEBUG
  23. #include <sys/socket.h>
  24. #include <netinet/in.h>
  25. #include <netinet/tcp.h>
  26. #endif
  27. #include <network/TcpSocket.h>
  28. #include <rfb/VNCSConnectionST.h>
  29. #include <rfb/LogWriter.h>
  30. #include <rfb/Security.h>
  31. #include <rfb/screenTypes.h>
  32. #include <rfb/fenceTypes.h>
  33. #include <rfb/ServerCore.h>
  34. #include <rfb/ComparingUpdateTracker.h>
  35. #include <rfb/KeyRemapper.h>
  36. #include <rfb/Encoder.h>
  37. #define XK_MISCELLANY
  38. #define XK_XKB_KEYS
  39. #include <rfb/keysymdef.h>
  40. using namespace rfb;
  41. static LogWriter vlog("VNCSConnST");
  42. // This window should get us going fairly fast on a decent bandwidth network.
  43. // If it's too high, it will rapidly be reduced and stay low.
  44. static const unsigned INITIAL_WINDOW = 16384;
  45. // TCP's minimal window is 3*MSS. But since we don't know the MSS, we
  46. // make a guess at 4 KiB (it's probaly a bit higher).
  47. static const unsigned MINIMUM_WINDOW = 4096;
  48. // The current default maximum window for Linux (4 MiB). Should be a good
  49. // limit for now...
  50. static const unsigned MAXIMUM_WINDOW = 4194304;
  51. struct RTTInfo {
  52. struct timeval tv;
  53. int offset;
  54. unsigned inFlight;
  55. };
  56. VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
  57. bool reverse)
  58. : SConnection(reverse), sock(s), inProcessMessages(false),
  59. pendingSyncFence(false), syncFence(false), fenceFlags(0),
  60. fenceDataLen(0), fenceData(NULL),
  61. baseRTT(-1), minRTT(-1), seenCongestion(false), pingCounter(0),
  62. ackedOffset(0), sentOffset(0), congWindow(0), congestionTimer(this),
  63. server(server_),
  64. updates(false), image_getter(server->useEconomicTranslate),
  65. drawRenderedCursor(false), removeRenderedCursor(false),
  66. continuousUpdates(false),
  67. updateTimer(this), pointerEventTime(0),
  68. accessRights(AccessDefault), startTime(time(0))
  69. {
  70. setStreams(&sock->inStream(), &sock->outStream());
  71. peerEndpoint.buf = sock->getPeerEndpoint();
  72. VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
  73. memset(encoders, 0, sizeof(encoders));
  74. // Configure the socket
  75. setSocketTimeouts();
  76. lastEventTime = time(0);
  77. server->clients.push_front(this);
  78. }
  79. VNCSConnectionST::~VNCSConnectionST()
  80. {
  81. // If we reach here then VNCServerST is deleting us!
  82. VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
  83. peerEndpoint.buf,
  84. (closeReason.buf) ? closeReason.buf : "");
  85. // Release any keys the client still had pressed
  86. std::set<rdr::U32>::iterator i;
  87. for (i=pressedKeys.begin(); i!=pressedKeys.end(); i++)
  88. server->desktop->keyEvent(*i, false);
  89. if (server->pointerClient == this)
  90. server->pointerClient = 0;
  91. // Remove this client from the server
  92. server->clients.remove(this);
  93. for (int i = 0; i <= encodingMax; i++)
  94. delete encoders[i];
  95. delete [] fenceData;
  96. }
  97. // Methods called from VNCServerST
  98. bool VNCSConnectionST::init()
  99. {
  100. try {
  101. initialiseProtocol();
  102. } catch (rdr::Exception& e) {
  103. close(e.str());
  104. return false;
  105. }
  106. return true;
  107. }
  108. void VNCSConnectionST::close(const char* reason)
  109. {
  110. // Log the reason for the close
  111. if (!closeReason.buf)
  112. closeReason.buf = strDup(reason);
  113. else
  114. vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
  115. if (authenticated()) {
  116. server->lastDisconnectTime = time(0);
  117. }
  118. // Just shutdown the socket and mark our state as closing. Eventually the
  119. // calling code will call VNCServerST's removeSocket() method causing us to
  120. // be deleted.
  121. sock->shutdown();
  122. setState(RFBSTATE_CLOSING);
  123. }
  124. void VNCSConnectionST::processMessages()
  125. {
  126. if (state() == RFBSTATE_CLOSING) return;
  127. try {
  128. // - Now set appropriate socket timeouts and process data
  129. setSocketTimeouts();
  130. inProcessMessages = true;
  131. // Get the underlying TCP layer to build large packets if we send
  132. // multiple small responses.
  133. network::TcpSocket::cork(sock->getFd(), true);
  134. while (getInStream()->checkNoWait(1)) {
  135. if (pendingSyncFence) {
  136. syncFence = true;
  137. pendingSyncFence = false;
  138. }
  139. processMsg();
  140. if (syncFence) {
  141. writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
  142. syncFence = false;
  143. }
  144. }
  145. // Flush out everything in case we go idle after this.
  146. network::TcpSocket::cork(sock->getFd(), false);
  147. inProcessMessages = false;
  148. // If there were anything requiring an update, try to send it here.
  149. // We wait until now with this to aggregate responses and to give
  150. // higher priority to user actions such as keyboard and pointer events.
  151. writeFramebufferUpdate();
  152. } catch (rdr::EndOfStream&) {
  153. close("Clean disconnection");
  154. } catch (rdr::Exception &e) {
  155. close(e.str());
  156. }
  157. }
  158. void VNCSConnectionST::pixelBufferChange()
  159. {
  160. try {
  161. if (!authenticated()) return;
  162. if (cp.width && cp.height && (server->pb->width() != cp.width ||
  163. server->pb->height() != cp.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 renderedCursorRect
  169. // because that might be added to updates in writeFramebufferUpdate().
  170. //updates.intersect(server->pb->getRect());
  171. //
  172. //if (server->pb->width() > cp.width)
  173. // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
  174. // server->pb->height()));
  175. //if (server->pb->height() > cp.height)
  176. // updates.add_changed(Rect(0, cp.height, cp.width,
  177. // server->pb->height()));
  178. renderedCursorRect = renderedCursorRect.intersect(server->pb->getRect());
  179. cp.width = server->pb->width();
  180. cp.height = server->pb->height();
  181. cp.screenLayout = server->screenLayout;
  182. if (state() == RFBSTATE_NORMAL) {
  183. // We should only send EDS to client asking for both
  184. if (!writer()->writeExtendedDesktopSize()) {
  185. if (!writer()->writeSetDesktopSize()) {
  186. close("Client does not support desktop resize");
  187. return;
  188. }
  189. }
  190. }
  191. }
  192. // Just update the whole screen at the moment because we're too lazy to
  193. // work out what's actually changed.
  194. updates.clear();
  195. updates.add_changed(server->pb->getRect());
  196. vlog.debug("pixel buffer changed - re-initialising image getter");
  197. image_getter.init(server->pb, cp.pf(), writer());
  198. writeFramebufferUpdate();
  199. } catch(rdr::Exception &e) {
  200. close(e.str());
  201. }
  202. }
  203. void VNCSConnectionST::writeFramebufferUpdateOrClose()
  204. {
  205. try {
  206. writeFramebufferUpdate();
  207. } catch(rdr::Exception &e) {
  208. close(e.str());
  209. }
  210. }
  211. void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
  212. {
  213. try {
  214. screenLayoutChange(reason);
  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. } catch(rdr::Exception& e) {
  243. close(e.str());
  244. }
  245. }
  246. void VNCSConnectionST::setCursorOrClose()
  247. {
  248. try {
  249. setCursor();
  250. } catch(rdr::Exception& e) {
  251. close(e.str());
  252. }
  253. }
  254. int VNCSConnectionST::checkIdleTimeout()
  255. {
  256. int idleTimeout = rfb::Server::idleTimeout;
  257. if (idleTimeout == 0) return 0;
  258. if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
  259. idleTimeout = 15; // minimum of 15 seconds while authenticating
  260. time_t now = time(0);
  261. if (now < lastEventTime) {
  262. // Someone must have set the time backwards. Set lastEventTime so that the
  263. // idleTimeout will count from now.
  264. vlog.info("Time has gone backwards - resetting idle timeout");
  265. lastEventTime = now;
  266. }
  267. int timeLeft = lastEventTime + idleTimeout - now;
  268. if (timeLeft < -60) {
  269. // Our callback is over a minute late - someone must have set the time
  270. // forwards. Set lastEventTime so that the idleTimeout will count from
  271. // now.
  272. vlog.info("Time has gone forwards - resetting idle timeout");
  273. lastEventTime = now;
  274. return secsToMillis(idleTimeout);
  275. }
  276. if (timeLeft <= 0) {
  277. close("Idle timeout");
  278. return 0;
  279. }
  280. return secsToMillis(timeLeft);
  281. }
  282. bool VNCSConnectionST::getComparerState()
  283. {
  284. // We interpret a low compression level as an indication that the client
  285. // wants to prioritise CPU usage over bandwidth, and hence disable the
  286. // comparing update tracker.
  287. return (cp.compressLevel == -1) || (cp.compressLevel > 1);
  288. }
  289. // renderedCursorChange() is called whenever the server-side rendered cursor
  290. // changes shape or position. It ensures that the next update will clean up
  291. // the old rendered cursor and if necessary draw the new rendered cursor.
  292. void VNCSConnectionST::renderedCursorChange()
  293. {
  294. if (state() != RFBSTATE_NORMAL) return;
  295. if (!renderedCursorRect.is_empty())
  296. removeRenderedCursor = true;
  297. if (needRenderedCursor()) {
  298. drawRenderedCursor = true;
  299. writeFramebufferUpdateOrClose();
  300. }
  301. }
  302. // needRenderedCursor() returns true if this client needs the server-side
  303. // rendered cursor. This may be because it does not support local cursor or
  304. // because the current cursor position has not been set by this client.
  305. // Unfortunately we can't know for sure when the current cursor position has
  306. // been set by this client. We guess that this is the case when the current
  307. // cursor position is the same as the last pointer event from this client, or
  308. // if it is a very short time since this client's last pointer event (up to a
  309. // second). [ Ideally we should do finer-grained timing here and make the time
  310. // configurable, but I don't think it's that important. ]
  311. bool VNCSConnectionST::needRenderedCursor()
  312. {
  313. bool pointerpos = (!server->cursorPos.equals(pointerEventPos) && (time(0) - pointerEventTime) > 0);
  314. return (state() == RFBSTATE_NORMAL
  315. && ((!cp.supportsLocalCursor && !cp.supportsLocalXCursor) || pointerpos));
  316. }
  317. void VNCSConnectionST::approveConnectionOrClose(bool accept,
  318. const char* reason)
  319. {
  320. try {
  321. approveConnection(accept, reason);
  322. } catch (rdr::Exception& e) {
  323. close(e.str());
  324. }
  325. }
  326. // -=- Callbacks from SConnection
  327. void VNCSConnectionST::authSuccess()
  328. {
  329. lastEventTime = time(0);
  330. server->startDesktop();
  331. // - Set the connection parameters appropriately
  332. cp.width = server->pb->width();
  333. cp.height = server->pb->height();
  334. cp.screenLayout = server->screenLayout;
  335. cp.setName(server->getName());
  336. // - Set the default pixel format
  337. cp.setPF(server->pb->getPF());
  338. char buffer[256];
  339. cp.pf().print(buffer, 256);
  340. vlog.info("Server default pixel format %s", buffer);
  341. image_getter.init(server->pb, cp.pf(), 0);
  342. // - Mark the entire display as "dirty"
  343. updates.add_changed(server->pb->getRect());
  344. startTime = time(0);
  345. // - Bootstrap the congestion control
  346. ackedOffset = sock->outStream().length();
  347. congWindow = INITIAL_WINDOW;
  348. }
  349. void VNCSConnectionST::queryConnection(const char* userName)
  350. {
  351. // - Authentication succeeded - clear from blacklist
  352. CharArray name; name.buf = sock->getPeerAddress();
  353. server->blHosts->clearBlackmark(name.buf);
  354. // - Special case to provide a more useful error message
  355. if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
  356. server->authClientCount() > 0) {
  357. approveConnection(false, "The server is already in use");
  358. return;
  359. }
  360. // - Does the client have the right to bypass the query?
  361. if (reverseConnection ||
  362. !(rfb::Server::queryConnect || sock->requiresQuery()) ||
  363. (accessRights & AccessNoQuery))
  364. {
  365. approveConnection(true);
  366. return;
  367. }
  368. // - Get the server to display an Accept/Reject dialog, if required
  369. // If a dialog is displayed, the result will be PENDING, and the
  370. // server will call approveConnection at a later time
  371. CharArray reason;
  372. VNCServerST::queryResult qr = server->queryConnection(sock, userName,
  373. &reason.buf);
  374. if (qr == VNCServerST::PENDING)
  375. return;
  376. // - If server returns ACCEPT/REJECT then pass result to SConnection
  377. approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
  378. }
  379. void VNCSConnectionST::clientInit(bool shared)
  380. {
  381. lastEventTime = time(0);
  382. if (rfb::Server::alwaysShared || reverseConnection) shared = true;
  383. if (rfb::Server::neverShared) shared = false;
  384. if (!shared) {
  385. if (rfb::Server::disconnectClients) {
  386. // - Close all the other connected clients
  387. vlog.debug("non-shared connection - closing clients");
  388. server->closeClients("Non-shared connection requested", getSock());
  389. } else {
  390. // - Refuse this connection if there are existing clients, in addition to
  391. // this one
  392. if (server->authClientCount() > 1) {
  393. close("Server is already in use");
  394. return;
  395. }
  396. }
  397. }
  398. SConnection::clientInit(shared);
  399. }
  400. void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
  401. {
  402. SConnection::setPixelFormat(pf);
  403. char buffer[256];
  404. pf.print(buffer, 256);
  405. vlog.info("Client pixel format %s", buffer);
  406. image_getter.init(server->pb, pf, writer());
  407. setCursor();
  408. }
  409. void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
  410. {
  411. pointerEventTime = lastEventTime = time(0);
  412. server->lastUserInputTime = lastEventTime;
  413. if (!(accessRights & AccessPtrEvents)) return;
  414. if (!rfb::Server::acceptPointerEvents) return;
  415. if (!server->pointerClient || server->pointerClient == this) {
  416. pointerEventPos = pos;
  417. if (buttonMask)
  418. server->pointerClient = this;
  419. else
  420. server->pointerClient = 0;
  421. server->desktop->pointerEvent(pointerEventPos, buttonMask);
  422. }
  423. }
  424. class VNCSConnectionSTShiftPresser {
  425. public:
  426. VNCSConnectionSTShiftPresser(SDesktop* desktop_)
  427. : desktop(desktop_), pressed(false) {}
  428. ~VNCSConnectionSTShiftPresser() {
  429. if (pressed) { desktop->keyEvent(XK_Shift_L, false); }
  430. }
  431. void press() {
  432. desktop->keyEvent(XK_Shift_L, true);
  433. pressed = true;
  434. }
  435. SDesktop* desktop;
  436. bool pressed;
  437. };
  438. // keyEvent() - record in the pressedKeys which keys were pressed. Allow
  439. // multiple down events (for autorepeat), but only allow a single up event.
  440. void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
  441. lastEventTime = time(0);
  442. server->lastUserInputTime = lastEventTime;
  443. if (!(accessRights & AccessKeyEvents)) return;
  444. if (!rfb::Server::acceptKeyEvents) return;
  445. // Remap the key if required
  446. if (server->keyRemapper)
  447. key = server->keyRemapper->remapKey(key);
  448. // Turn ISO_Left_Tab into shifted Tab.
  449. VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
  450. if (key == XK_ISO_Left_Tab) {
  451. if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
  452. pressedKeys.find(XK_Shift_R) == pressedKeys.end())
  453. shiftPresser.press();
  454. key = XK_Tab;
  455. }
  456. if (down) {
  457. pressedKeys.insert(key);
  458. } else {
  459. if (!pressedKeys.erase(key)) return;
  460. }
  461. server->desktop->keyEvent(key, down);
  462. }
  463. void VNCSConnectionST::clientCutText(const char* str, int len)
  464. {
  465. if (!(accessRights & AccessCutText)) return;
  466. if (!rfb::Server::acceptCutText) return;
  467. server->desktop->clientCutText(str, len);
  468. }
  469. void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
  470. {
  471. Rect safeRect;
  472. if (!(accessRights & AccessView)) return;
  473. SConnection::framebufferUpdateRequest(r, incremental);
  474. // Check that the client isn't sending crappy requests
  475. if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
  476. vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
  477. r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
  478. safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
  479. } else {
  480. safeRect = r;
  481. }
  482. // Just update the requested region.
  483. // Framebuffer update will be sent a bit later, see processMessages().
  484. Region reqRgn(r);
  485. if (!incremental || !continuousUpdates)
  486. requested.assign_union(reqRgn);
  487. if (!incremental) {
  488. // Non-incremental update - treat as if area requested has changed
  489. updates.add_changed(reqRgn);
  490. server->comparer->add_changed(reqRgn);
  491. // And send the screen layout to the client (which, unlike the
  492. // framebuffer dimensions, the client doesn't get during init)
  493. writer()->writeExtendedDesktopSize();
  494. // We do not send a DesktopSize since it only contains the
  495. // framebuffer size (which the client already should know) and
  496. // because some clients don't handle extra DesktopSize events
  497. // very well.
  498. }
  499. }
  500. void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
  501. const ScreenSet& layout)
  502. {
  503. unsigned int result;
  504. // Don't bother the desktop with an invalid configuration
  505. if (!layout.validate(fb_width, fb_height)) {
  506. writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
  507. fb_width, fb_height, layout);
  508. writeFramebufferUpdate();
  509. return;
  510. }
  511. // FIXME: the desktop will call back to VNCServerST and an extra set
  512. // of ExtendedDesktopSize messages will be sent. This is okay
  513. // protocol-wise, but unnecessary.
  514. result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
  515. writer()->writeExtendedDesktopSize(reasonClient, result,
  516. fb_width, fb_height, layout);
  517. // Only notify other clients on success
  518. if (result == resultSuccess) {
  519. if (server->screenLayout != layout)
  520. throw Exception("Desktop configured a different screen layout than requested");
  521. server->notifyScreenLayoutChange(this);
  522. }
  523. // but always send back a reply to the requesting client
  524. // (do this last as it might throw an exception on socket errors)
  525. writeFramebufferUpdate();
  526. }
  527. void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
  528. {
  529. if (flags & fenceFlagRequest) {
  530. if (flags & fenceFlagSyncNext) {
  531. pendingSyncFence = true;
  532. fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
  533. fenceDataLen = len;
  534. delete [] fenceData;
  535. if (len > 0) {
  536. fenceData = new char[len];
  537. memcpy(fenceData, data, len);
  538. }
  539. return;
  540. }
  541. // We handle everything synchronously so we trivially honor these modes
  542. flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
  543. writer()->writeFence(flags, len, data);
  544. return;
  545. }
  546. struct RTTInfo rttInfo;
  547. switch (len) {
  548. case 0:
  549. // Initial dummy fence;
  550. break;
  551. case sizeof(struct RTTInfo):
  552. memcpy(&rttInfo, data, sizeof(struct RTTInfo));
  553. handleRTTPong(rttInfo);
  554. break;
  555. default:
  556. vlog.error("Fence response of unexpected size received");
  557. }
  558. }
  559. void VNCSConnectionST::enableContinuousUpdates(bool enable,
  560. int x, int y, int w, int h)
  561. {
  562. Rect rect;
  563. if (!cp.supportsFence || !cp.supportsContinuousUpdates)
  564. throw Exception("Client tried to enable continuous updates when not allowed");
  565. continuousUpdates = enable;
  566. rect.setXYWH(x, y, w, h);
  567. cuRegion.reset(rect);
  568. if (enable) {
  569. requested.clear();
  570. writeFramebufferUpdate();
  571. } else {
  572. writer()->writeEndOfContinuousUpdates();
  573. }
  574. }
  575. // supportsLocalCursor() is called whenever the status of
  576. // cp.supportsLocalCursor has changed. If the client does now support local
  577. // cursor, we make sure that the old server-side rendered cursor is cleaned up
  578. // and the cursor is sent to the client.
  579. void VNCSConnectionST::supportsLocalCursor()
  580. {
  581. if (cp.supportsLocalCursor || cp.supportsLocalXCursor) {
  582. if (!renderedCursorRect.is_empty())
  583. removeRenderedCursor = true;
  584. drawRenderedCursor = false;
  585. setCursor();
  586. }
  587. }
  588. void VNCSConnectionST::supportsFence()
  589. {
  590. writer()->writeFence(fenceFlagRequest, 0, NULL);
  591. }
  592. void VNCSConnectionST::supportsContinuousUpdates()
  593. {
  594. // We refuse to use continuous updates if we cannot monitor the buffer
  595. // usage using fences.
  596. if (!cp.supportsFence)
  597. return;
  598. writer()->writeEndOfContinuousUpdates();
  599. }
  600. void VNCSConnectionST::writeSetCursorCallback()
  601. {
  602. if (cp.supportsLocalXCursor) {
  603. Pixel pix0, pix1;
  604. rdr::U8Array bitmap(server->cursor.getBitmap(&pix0, &pix1));
  605. if (bitmap.buf) {
  606. // The client supports XCursor and the cursor only has two
  607. // colors. Use the XCursor encoding.
  608. writer()->writeSetXCursor(server->cursor.width(),
  609. server->cursor.height(),
  610. server->cursor.hotspot.x,
  611. server->cursor.hotspot.y,
  612. bitmap.buf, server->cursor.mask.buf);
  613. return;
  614. } else {
  615. // More than two colors
  616. if (!cp.supportsLocalCursor) {
  617. // FIXME: We could reduce to two colors.
  618. vlog.info("Unable to send multicolor cursor: RichCursor not supported by client");
  619. return;
  620. }
  621. }
  622. }
  623. // Use RichCursor
  624. rdr::U8* transData = writer()->getImageBuf(server->cursor.area());
  625. image_getter.translatePixels(server->cursor.data, transData,
  626. server->cursor.area());
  627. writer()->writeSetCursor(server->cursor.width(),
  628. server->cursor.height(),
  629. server->cursor.hotspot,
  630. transData, server->cursor.mask.buf);
  631. }
  632. bool VNCSConnectionST::handleTimeout(Timer* t)
  633. {
  634. try {
  635. if (t == &updateTimer)
  636. writeFramebufferUpdate();
  637. else if (t == &congestionTimer)
  638. updateCongestion();
  639. } catch (rdr::Exception& e) {
  640. close(e.str());
  641. }
  642. return false;
  643. }
  644. void VNCSConnectionST::writeRTTPing()
  645. {
  646. struct RTTInfo rttInfo;
  647. if (!cp.supportsFence)
  648. return;
  649. memset(&rttInfo, 0, sizeof(struct RTTInfo));
  650. gettimeofday(&rttInfo.tv, NULL);
  651. rttInfo.offset = sock->outStream().length();
  652. rttInfo.inFlight = rttInfo.offset - ackedOffset;
  653. // We need to make sure any old update are already processed by the
  654. // time we get the response back. This allows us to reliably throttle
  655. // back on client overload, as well as network overload.
  656. writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
  657. sizeof(struct RTTInfo), (const char*)&rttInfo);
  658. pingCounter++;
  659. sentOffset = rttInfo.offset;
  660. // Let some data flow before we adjust the settings
  661. if (!congestionTimer.isStarted())
  662. congestionTimer.start(__rfbmin(baseRTT * 2, 100));
  663. }
  664. void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
  665. {
  666. unsigned rtt, delay;
  667. int bdp;
  668. pingCounter--;
  669. rtt = msSince(&rttInfo.tv);
  670. if (rtt < 1)
  671. rtt = 1;
  672. ackedOffset = rttInfo.offset;
  673. // Try to estimate wire latency by tracking lowest seen latency
  674. if (rtt < baseRTT)
  675. baseRTT = rtt;
  676. if (rttInfo.inFlight > congWindow) {
  677. seenCongestion = true;
  678. // Estimate added delay because of overtaxed buffers
  679. delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
  680. if (delay < rtt)
  681. rtt -= delay;
  682. else
  683. rtt = 1;
  684. // If we underestimate the congestion window, then we'll get a latency
  685. // that's less than the wire latency, which will confuse other portions
  686. // of the code.
  687. if (rtt < baseRTT)
  688. rtt = baseRTT;
  689. }
  690. // We only keep track of the minimum latency seen (for a given interval)
  691. // on the basis that we want to avoid continous buffer issue, but don't
  692. // mind (or even approve of) bursts.
  693. if (rtt < minRTT)
  694. minRTT = rtt;
  695. }
  696. bool VNCSConnectionST::isCongested()
  697. {
  698. int offset;
  699. // Stuff still waiting in the send buffer?
  700. if (sock->outStream().bufferUsage() > 0)
  701. return true;
  702. if (!cp.supportsFence)
  703. return false;
  704. // Idle for too long? (and no data on the wire)
  705. //
  706. // FIXME: This should really just be one baseRTT, but we're getting
  707. // problems with triggering the idle timeout on each update.
  708. // Maybe we need to use a moving average for the wire latency
  709. // instead of baseRTT.
  710. if ((sentOffset == ackedOffset) &&
  711. (sock->outStream().getIdleTime() > 2 * baseRTT)) {
  712. #ifdef CONGESTION_DEBUG
  713. if (congWindow > INITIAL_WINDOW)
  714. fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
  715. INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
  716. #endif
  717. // Close congestion window and allow a transfer
  718. // FIXME: Reset baseRTT like Linux Vegas?
  719. congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
  720. return false;
  721. }
  722. offset = sock->outStream().length();
  723. // FIXME: Should we compensate for non-update data?
  724. // (i.e. use sentOffset instead of offset)
  725. if ((offset - ackedOffset) < congWindow)
  726. return false;
  727. // If we just have one outstanding "ping", that means the client has
  728. // started receiving our update. In order to not regress compared to
  729. // before we had congestion avoidance, we allow another update here.
  730. // This could further clog up the tubes, but congestion control isn't
  731. // really working properly right now anyway as the wire would otherwise
  732. // be idle for at least RTT/2.
  733. if (pingCounter == 1)
  734. return false;
  735. return true;
  736. }
  737. void VNCSConnectionST::updateCongestion()
  738. {
  739. unsigned diff;
  740. if (!seenCongestion)
  741. return;
  742. diff = minRTT - baseRTT;
  743. if (diff > __rfbmin(100, baseRTT)) {
  744. // Way too fast
  745. congWindow = congWindow * baseRTT / minRTT;
  746. } else if (diff > __rfbmin(50, baseRTT/2)) {
  747. // Slightly too fast
  748. congWindow -= 4096;
  749. } else if (diff < 5) {
  750. // Way too slow
  751. congWindow += 8192;
  752. } else if (diff < 25) {
  753. // Too slow
  754. congWindow += 4096;
  755. }
  756. if (congWindow < MINIMUM_WINDOW)
  757. congWindow = MINIMUM_WINDOW;
  758. if (congWindow > MAXIMUM_WINDOW)
  759. congWindow = MAXIMUM_WINDOW;
  760. #ifdef CONGESTION_DEBUG
  761. fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
  762. minRTT, baseRTT, congWindow / 1024,
  763. congWindow * 8.0 / baseRTT / 1000.0);
  764. #ifdef TCP_INFO
  765. struct tcp_info tcp_info;
  766. socklen_t tcp_info_length;
  767. tcp_info_length = sizeof(tcp_info);
  768. if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
  769. (void *)&tcp_info, &tcp_info_length) == 0) {
  770. fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
  771. tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
  772. tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
  773. }
  774. #endif
  775. #endif
  776. minRTT = -1;
  777. seenCongestion = false;
  778. }
  779. void VNCSConnectionST::writeFramebufferUpdate()
  780. {
  781. Region req;
  782. UpdateInfo ui;
  783. bool needNewUpdateInfo;
  784. updateTimer.stop();
  785. // We're in the middle of processing a command that's supposed to be
  786. // synchronised. Allowing an update to slip out right now might violate
  787. // that synchronisation.
  788. if (syncFence)
  789. return;
  790. // We try to aggregate responses, so don't send out anything whilst we
  791. // still have incoming messages. processMessages() will give us another
  792. // chance to run once things are idle.
  793. if (inProcessMessages)
  794. return;
  795. if (state() != RFBSTATE_NORMAL)
  796. return;
  797. if (requested.is_empty() && !continuousUpdates)
  798. return;
  799. // Check that we actually have some space on the link and retry in a
  800. // bit if things are congested.
  801. if (isCongested()) {
  802. updateTimer.start(50);
  803. return;
  804. }
  805. // In continuous mode, we will be outputting at least three distinct
  806. // messages. We need to aggregate these in order to not clog up TCP's
  807. // congestion window.
  808. network::TcpSocket::cork(sock->getFd(), true);
  809. // First take care of any updates that cannot contain framebuffer data
  810. // changes.
  811. if (writer()->needNoDataUpdate()) {
  812. writer()->writeNoDataUpdate();
  813. requested.clear();
  814. if (!continuousUpdates)
  815. goto out;
  816. }
  817. updates.enable_copyrect(cp.useCopyRect);
  818. // Fetch updates from server object, and see if we are allowed to send
  819. // anything right now (the framebuffer might have changed in ways we
  820. // haven't yet been informed of).
  821. if (!server->checkUpdate())
  822. goto out;
  823. // Get the lists of updates. Prior to exporting the data to the `ui' object,
  824. // getUpdateInfo() will normalize the `updates' object such way that its
  825. // `changed' and `copied' regions would not intersect.
  826. if (continuousUpdates)
  827. req = cuRegion.union_(requested);
  828. else
  829. req = requested;
  830. updates.getUpdateInfo(&ui, req);
  831. needNewUpdateInfo = false;
  832. // If the previous position of the rendered cursor overlaps the source of the
  833. // copy, then when the copy happens the corresponding rectangle in the
  834. // destination will be wrong, so add it to the changed region.
  835. if (!ui.copied.is_empty() && !renderedCursorRect.is_empty()) {
  836. Rect bogusCopiedCursor = (renderedCursorRect.translate(ui.copy_delta)
  837. .intersect(server->pb->getRect()));
  838. if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
  839. updates.add_changed(bogusCopiedCursor);
  840. needNewUpdateInfo = true;
  841. }
  842. }
  843. // If we need to remove the old rendered cursor, just add the rectangle to
  844. // the changed region.
  845. if (removeRenderedCursor) {
  846. updates.add_changed(renderedCursorRect);
  847. needNewUpdateInfo = true;
  848. renderedCursorRect.clear();
  849. removeRenderedCursor = false;
  850. }
  851. // Return if there is nothing to send the client.
  852. if (updates.is_empty() && !writer()->needFakeUpdate() && !drawRenderedCursor)
  853. goto out;
  854. // The `updates' object could change, make sure we have valid update info.
  855. if (needNewUpdateInfo)
  856. updates.getUpdateInfo(&ui, req);
  857. // If the client needs a server-side rendered cursor, work out the cursor
  858. // rectangle. If it's empty then don't bother drawing it, but if it overlaps
  859. // with the update region, we need to draw the rendered cursor regardless of
  860. // whether it has changed.
  861. if (needRenderedCursor()) {
  862. renderedCursorRect
  863. = (server->renderedCursor.getRect(server->renderedCursorTL)
  864. .intersect(req.get_bounding_rect()));
  865. if (renderedCursorRect.is_empty()) {
  866. drawRenderedCursor = false;
  867. } else if (!ui.changed.union_(ui.copied)
  868. .intersect(renderedCursorRect).is_empty()) {
  869. drawRenderedCursor = true;
  870. }
  871. // We could remove the new cursor rect from updates here. It's not clear
  872. // whether this is worth it. If we do remove it, then we won't draw over
  873. // the same bit of screen twice, but we have the overhead of a more complex
  874. // region.
  875. //if (drawRenderedCursor) {
  876. // updates.subtract(renderedCursorRect);
  877. // updates.getUpdateInfo(&ui, req);
  878. //}
  879. }
  880. if (!ui.is_empty() || writer()->needFakeUpdate() || drawRenderedCursor) {
  881. std::vector<Rect> rects;
  882. std::vector<Rect>::const_iterator i;
  883. int encoding;
  884. // Make sure the encoder has the latest settings
  885. encoding = cp.currentEncoding();
  886. if (!encoders[encoding])
  887. encoders[encoding] = Encoder::createEncoder(encoding, writer());
  888. encoders[encoding]->setCompressLevel(cp.compressLevel);
  889. encoders[encoding]->setQualityLevel(cp.qualityLevel);
  890. encoders[encoding]->setFineQualityLevel(cp.fineQualityLevel,
  891. cp.subsampling);
  892. // Compute the number of rectangles. Tight encoder makes the things more
  893. // complicated as compared to the original VNC4.
  894. int nRects = (ui.copied.numRects() +
  895. (drawRenderedCursor ? 1 : 0));
  896. ui.changed.get_rects(&rects);
  897. for (i = rects.begin(); i != rects.end(); i++) {
  898. if (i->width() && i->height()) {
  899. int nUpdateRects = encoders[encoding]->getNumRects(*i);
  900. if (nUpdateRects == 0 && cp.currentEncoding() == encodingTight) {
  901. // With Tight encoding and LastRect support, the client does not
  902. // care about the number of rectangles in the update - it will
  903. // stop parsing when it encounters a LastRect "rectangle".
  904. // In this case, pretend to send 65535 rectangles.
  905. nRects = 0xFFFF; break;
  906. }
  907. else
  908. nRects += nUpdateRects;
  909. }
  910. }
  911. writeRTTPing();
  912. writer()->writeFramebufferUpdateStart(nRects);
  913. ui.copied.get_rects(&rects);
  914. for (i = rects.begin(); i != rects.end(); i++)
  915. writer()->writeCopyRect(*i, i->tl.x - ui.copy_delta.x,
  916. i->tl.y - ui.copy_delta.y);
  917. ui.changed.get_rects(&rects);
  918. for (i = rects.begin(); i != rects.end(); i++)
  919. encoders[encoding]->writeRect(*i, &image_getter);
  920. if (drawRenderedCursor) {
  921. image_getter.setPixelBuffer(&server->renderedCursor);
  922. image_getter.setOffset(server->renderedCursorTL);
  923. encoders[encoding]->writeRect(renderedCursorRect, &image_getter);
  924. image_getter.setPixelBuffer(server->pb);
  925. image_getter.setOffset(Point(0,0));
  926. drawRenderedCursor = false;
  927. }
  928. writer()->writeFramebufferUpdateEnd();
  929. writeRTTPing();
  930. requested.clear();
  931. updates.clear();
  932. }
  933. out:
  934. network::TcpSocket::cork(sock->getFd(), false);
  935. }
  936. void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
  937. {
  938. if (!authenticated())
  939. return;
  940. cp.screenLayout = server->screenLayout;
  941. if (state() != RFBSTATE_NORMAL)
  942. return;
  943. writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
  944. cp.screenLayout);
  945. writeFramebufferUpdate();
  946. }
  947. // setCursor() is called whenever the cursor has changed shape or pixel format.
  948. // If the client supports local cursor then it will arrange for the cursor to
  949. // be sent to the client.
  950. void VNCSConnectionST::setCursor()
  951. {
  952. if (state() != RFBSTATE_NORMAL)
  953. return;
  954. if (!cp.supportsLocalCursor)
  955. return;
  956. writer()->cursorChange(this);
  957. writeFramebufferUpdate();
  958. }
  959. void VNCSConnectionST::setDesktopName(const char *name)
  960. {
  961. cp.setName(name);
  962. if (state() != RFBSTATE_NORMAL)
  963. return;
  964. if (!writer()->writeSetDesktopName()) {
  965. fprintf(stderr, "Client does not support desktop rename\n");
  966. return;
  967. }
  968. writeFramebufferUpdate();
  969. }
  970. void VNCSConnectionST::setSocketTimeouts()
  971. {
  972. int timeoutms = rfb::Server::clientWaitTimeMillis;
  973. soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
  974. if (timeoutms == 0)
  975. timeoutms = -1;
  976. sock->inStream().setTimeout(timeoutms);
  977. sock->outStream().setTimeout(timeoutms);
  978. }
  979. char* VNCSConnectionST::getStartTime()
  980. {
  981. char* result = ctime(&startTime);
  982. result[24] = '\0';
  983. return result;
  984. }
  985. void VNCSConnectionST::setStatus(int status)
  986. {
  987. switch (status) {
  988. case 0:
  989. accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
  990. break;
  991. case 1:
  992. accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents) | AccessView;
  993. break;
  994. case 2:
  995. accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
  996. break;
  997. }
  998. framebufferUpdateRequest(server->pb->getRect(), false);
  999. }
  1000. int VNCSConnectionST::getStatus()
  1001. {
  1002. if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
  1003. return 0;
  1004. if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
  1005. return 1;
  1006. if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
  1007. return 2;
  1008. return 4;
  1009. }