Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

VNCSConnectionST.cxx 32KB

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