You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VNCSConnectionST.cxx 33KB

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