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

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