blob: 452f7246fc2259ffed349103ac9838998e37d7e5 [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00002 * Copyright 2009-2011 Pierre Ossman for Cendio AB
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00003 *
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
Pierre Ossman1b478e52011-11-15 12:08:30 +000020// Debug output on what the congestion control is up to
21#undef CONGESTION_DEBUG
22
23#include <sys/time.h>
24
25#ifdef CONGESTION_DEBUG
26#include <sys/socket.h>
27#include <netinet/in.h>
28#include <netinet/tcp.h>
29#endif
30
Pierre Ossmana830bec2011-11-08 12:12:02 +000031#include <network/TcpSocket.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000032#include <rfb/VNCSConnectionST.h>
33#include <rfb/LogWriter.h>
Adam Tkac5a0caed2010-04-23 13:58:10 +000034#include <rfb/Security.h>
Pierre Ossmanc5e25602009-03-20 12:59:05 +000035#include <rfb/screenTypes.h>
Pierre Ossman2c764942011-11-14 15:54:30 +000036#include <rfb/fenceTypes.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000037#include <rfb/ServerCore.h>
38#include <rfb/ComparingUpdateTracker.h>
39#include <rfb/KeyRemapper.h>
40#define XK_MISCELLANY
41#define XK_XKB_KEYS
42#include <rfb/keysymdef.h>
43
44using namespace rfb;
45
46static LogWriter vlog("VNCSConnST");
47
Pierre Ossman1b478e52011-11-15 12:08:30 +000048// This window should get us going fairly fast on a decent bandwidth network.
49// If it's too high, it will rapidly be reduced and stay low.
50static const unsigned INITIAL_WINDOW = 16384;
51
52// TCP's minimal window is 3*MSS. But since we don't know the MSS, we
53// make a guess at 4 KiB (it's probaly a bit higher).
54static const unsigned MINIMUM_WINDOW = 4096;
55
56// The current default maximum window for Linux (4 MiB). Should be a good
57// limit for now...
58static const unsigned MAXIMUM_WINDOW = 4194304;
59
60struct RTTInfo {
61 struct timeval tv;
62 int offset;
63 unsigned inFlight;
64};
65
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000066VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
67 bool reverse)
Pierre Ossman2c764942011-11-14 15:54:30 +000068 : SConnection(reverse), sock(s), inProcessMessages(false),
Pierre Ossmanb8b1e962012-07-20 10:47:00 +000069 pendingSyncFence(false), syncFence(false), fenceFlags(0),
70 fenceDataLen(0), fenceData(NULL),
Pierre Ossman1b478e52011-11-15 12:08:30 +000071 baseRTT(-1), minRTT(-1), seenCongestion(false), pingCounter(0),
72 ackedOffset(0), sentOffset(0), congWindow(0), congestionTimer(this),
Pierre Ossman2c764942011-11-14 15:54:30 +000073 server(server_),
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000074 updates(false), image_getter(server->useEconomicTranslate),
75 drawRenderedCursor(false), removeRenderedCursor(false),
Pierre Ossman1b478e52011-11-15 12:08:30 +000076 continuousUpdates(false),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000077 updateTimer(this), pointerEventTime(0),
78 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000079{
80 setStreams(&sock->inStream(), &sock->outStream());
81 peerEndpoint.buf = sock->getPeerEndpoint();
82 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
83
84 // Configure the socket
85 setSocketTimeouts();
86 lastEventTime = time(0);
87
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000088 server->clients.push_front(this);
89}
90
91
92VNCSConnectionST::~VNCSConnectionST()
93{
94 // If we reach here then VNCServerST is deleting us!
95 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
96 peerEndpoint.buf,
97 (closeReason.buf) ? closeReason.buf : "");
98
99 // Release any keys the client still had pressed
100 std::set<rdr::U32>::iterator i;
101 for (i=pressedKeys.begin(); i!=pressedKeys.end(); i++)
102 server->desktop->keyEvent(*i, false);
103 if (server->pointerClient == this)
104 server->pointerClient = 0;
105
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000106 // Remove this client from the server
107 server->clients.remove(this);
108
Pierre Ossman2c764942011-11-14 15:54:30 +0000109 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000110}
111
112
113// Methods called from VNCServerST
114
115bool VNCSConnectionST::init()
116{
117 try {
118 initialiseProtocol();
119 } catch (rdr::Exception& e) {
120 close(e.str());
121 return false;
122 }
123 return true;
124}
125
126void VNCSConnectionST::close(const char* reason)
127{
128 // Log the reason for the close
129 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000130 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000131 else
132 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
133
134 if (authenticated()) {
135 server->lastDisconnectTime = time(0);
136 }
137
138 // Just shutdown the socket and mark our state as closing. Eventually the
139 // calling code will call VNCServerST's removeSocket() method causing us to
140 // be deleted.
141 sock->shutdown();
142 setState(RFBSTATE_CLOSING);
143}
144
145
146void VNCSConnectionST::processMessages()
147{
148 if (state() == RFBSTATE_CLOSING) return;
149 try {
150 // - Now set appropriate socket timeouts and process data
151 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000152
153 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000154
Pierre Ossmana830bec2011-11-08 12:12:02 +0000155 // Get the underlying TCP layer to build large packets if we send
156 // multiple small responses.
157 network::TcpSocket::cork(sock->getFd(), true);
158
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000159 while (getInStream()->checkNoWait(1)) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000160 if (pendingSyncFence) {
161 syncFence = true;
162 pendingSyncFence = false;
163 }
164
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000165 processMsg();
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000166
Pierre Ossman2c764942011-11-14 15:54:30 +0000167 if (syncFence) {
168 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
169 syncFence = false;
170 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000171 }
172
Pierre Ossmana830bec2011-11-08 12:12:02 +0000173 // Flush out everything in case we go idle after this.
174 network::TcpSocket::cork(sock->getFd(), false);
175
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000176 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000177
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000178 // If there were anything requiring an update, try to send it here.
179 // We wait until now with this to aggregate responses and to give
180 // higher priority to user actions such as keyboard and pointer events.
181 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000182 } catch (rdr::EndOfStream&) {
183 close("Clean disconnection");
184 } catch (rdr::Exception &e) {
185 close(e.str());
186 }
187}
188
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000189void VNCSConnectionST::pixelBufferChange()
190{
191 try {
192 if (!authenticated()) return;
193 if (cp.width && cp.height && (server->pb->width() != cp.width ||
194 server->pb->height() != cp.height))
195 {
196 // We need to clip the next update to the new size, but also add any
197 // extra bits if it's bigger. If we wanted to do this exactly, something
198 // like the code below would do it, but at the moment we just update the
199 // entire new size. However, we do need to clip the renderedCursorRect
200 // because that might be added to updates in writeFramebufferUpdate().
201
202 //updates.intersect(server->pb->getRect());
203 //
204 //if (server->pb->width() > cp.width)
205 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
206 // server->pb->height()));
207 //if (server->pb->height() > cp.height)
208 // updates.add_changed(Rect(0, cp.height, cp.width,
209 // server->pb->height()));
210
211 renderedCursorRect = renderedCursorRect.intersect(server->pb->getRect());
212
213 cp.width = server->pb->width();
214 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000215 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000216 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000217 // We should only send EDS to client asking for both
218 if (!writer()->writeExtendedDesktopSize()) {
219 if (!writer()->writeSetDesktopSize()) {
220 close("Client does not support desktop resize");
221 return;
222 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000223 }
224 }
225 }
226 // Just update the whole screen at the moment because we're too lazy to
227 // work out what's actually changed.
228 updates.clear();
229 updates.add_changed(server->pb->getRect());
230 vlog.debug("pixel buffer changed - re-initialising image getter");
231 image_getter.init(server->pb, cp.pf(), writer());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000232 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000233 } catch(rdr::Exception &e) {
234 close(e.str());
235 }
236}
237
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000238void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000239{
240 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000241 writeFramebufferUpdate();
242 } catch(rdr::Exception &e) {
243 close(e.str());
244 }
245}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000246
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000247void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
248{
249 try {
250 screenLayoutChange(reason);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000251 } catch(rdr::Exception &e) {
252 close(e.str());
253 }
254}
255
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000256void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000257{
258 try {
259 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
260 } catch(rdr::Exception& e) {
261 close(e.str());
262 }
263}
264
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000265void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000266{
267 try {
268 if (!(accessRights & AccessCutText)) return;
269 if (!rfb::Server::sendCutText) return;
270 if (state() == RFBSTATE_NORMAL)
271 writer()->writeServerCutText(str, len);
272 } catch(rdr::Exception& e) {
273 close(e.str());
274 }
275}
276
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000277
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000278void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000279{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000280 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000281 setDesktopName(name);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000282 } catch(rdr::Exception& e) {
283 close(e.str());
284 }
285}
286
287
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000288void VNCSConnectionST::setCursorOrClose()
289{
290 try {
291 setCursor();
292 } catch(rdr::Exception& e) {
293 close(e.str());
294 }
295}
296
297
298int VNCSConnectionST::checkIdleTimeout()
299{
300 int idleTimeout = rfb::Server::idleTimeout;
301 if (idleTimeout == 0) return 0;
302 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
303 idleTimeout = 15; // minimum of 15 seconds while authenticating
304 time_t now = time(0);
305 if (now < lastEventTime) {
306 // Someone must have set the time backwards. Set lastEventTime so that the
307 // idleTimeout will count from now.
308 vlog.info("Time has gone backwards - resetting idle timeout");
309 lastEventTime = now;
310 }
311 int timeLeft = lastEventTime + idleTimeout - now;
312 if (timeLeft < -60) {
313 // Our callback is over a minute late - someone must have set the time
314 // forwards. Set lastEventTime so that the idleTimeout will count from
315 // now.
316 vlog.info("Time has gone forwards - resetting idle timeout");
317 lastEventTime = now;
318 return secsToMillis(idleTimeout);
319 }
320 if (timeLeft <= 0) {
321 close("Idle timeout");
322 return 0;
323 }
324 return secsToMillis(timeLeft);
325}
326
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000327
328bool VNCSConnectionST::getComparerState()
329{
330 // We interpret a low compression level as an indication that the client
331 // wants to prioritise CPU usage over bandwidth, and hence disable the
332 // comparing update tracker.
333 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
334}
335
336
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000337// renderedCursorChange() is called whenever the server-side rendered cursor
338// changes shape or position. It ensures that the next update will clean up
339// the old rendered cursor and if necessary draw the new rendered cursor.
340
341void VNCSConnectionST::renderedCursorChange()
342{
343 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000344 if (!renderedCursorRect.is_empty())
345 removeRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000346 if (needRenderedCursor()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000347 drawRenderedCursor = true;
Pierre Ossman6b0bc292011-12-21 13:17:54 +0000348 writeFramebufferUpdateOrClose();
349 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000350}
351
352// needRenderedCursor() returns true if this client needs the server-side
353// rendered cursor. This may be because it does not support local cursor or
354// because the current cursor position has not been set by this client.
355// Unfortunately we can't know for sure when the current cursor position has
356// been set by this client. We guess that this is the case when the current
357// cursor position is the same as the last pointer event from this client, or
358// if it is a very short time since this client's last pointer event (up to a
359// second). [ Ideally we should do finer-grained timing here and make the time
360// configurable, but I don't think it's that important. ]
361
362bool VNCSConnectionST::needRenderedCursor()
363{
Peter Ã…strandffeeb262010-02-10 09:29:00 +0000364 bool pointerpos = (!server->cursorPos.equals(pointerEventPos) && (time(0) - pointerEventTime) > 0);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000365 return (state() == RFBSTATE_NORMAL
Peter Ã…strandffeeb262010-02-10 09:29:00 +0000366 && ((!cp.supportsLocalCursor && !cp.supportsLocalXCursor) || pointerpos));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000367}
368
369
370void VNCSConnectionST::approveConnectionOrClose(bool accept,
371 const char* reason)
372{
373 try {
374 approveConnection(accept, reason);
375 } catch (rdr::Exception& e) {
376 close(e.str());
377 }
378}
379
380
381
382// -=- Callbacks from SConnection
383
384void VNCSConnectionST::authSuccess()
385{
386 lastEventTime = time(0);
387
388 server->startDesktop();
389
390 // - Set the connection parameters appropriately
391 cp.width = server->pb->width();
392 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000393 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000394 cp.setName(server->getName());
395
396 // - Set the default pixel format
397 cp.setPF(server->pb->getPF());
398 char buffer[256];
399 cp.pf().print(buffer, 256);
400 vlog.info("Server default pixel format %s", buffer);
401 image_getter.init(server->pb, cp.pf(), 0);
402
403 // - Mark the entire display as "dirty"
404 updates.add_changed(server->pb->getRect());
405 startTime = time(0);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000406
407 // - Bootstrap the congestion control
408 ackedOffset = sock->outStream().length();
409 congWindow = INITIAL_WINDOW;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000410}
411
412void VNCSConnectionST::queryConnection(const char* userName)
413{
414 // - Authentication succeeded - clear from blacklist
415 CharArray name; name.buf = sock->getPeerAddress();
416 server->blHosts->clearBlackmark(name.buf);
417
418 // - Special case to provide a more useful error message
419 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
420 server->authClientCount() > 0) {
421 approveConnection(false, "The server is already in use");
422 return;
423 }
424
425 // - Does the client have the right to bypass the query?
426 if (reverseConnection ||
427 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
428 (accessRights & AccessNoQuery))
429 {
430 approveConnection(true);
431 return;
432 }
433
434 // - Get the server to display an Accept/Reject dialog, if required
435 // If a dialog is displayed, the result will be PENDING, and the
436 // server will call approveConnection at a later time
437 CharArray reason;
438 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
439 &reason.buf);
440 if (qr == VNCServerST::PENDING)
441 return;
442
443 // - If server returns ACCEPT/REJECT then pass result to SConnection
444 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
445}
446
447void VNCSConnectionST::clientInit(bool shared)
448{
449 lastEventTime = time(0);
450 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
451 if (rfb::Server::neverShared) shared = false;
452 if (!shared) {
453 if (rfb::Server::disconnectClients) {
454 // - Close all the other connected clients
455 vlog.debug("non-shared connection - closing clients");
456 server->closeClients("Non-shared connection requested", getSock());
457 } else {
458 // - Refuse this connection if there are existing clients, in addition to
459 // this one
460 if (server->authClientCount() > 1) {
461 close("Server is already in use");
462 return;
463 }
464 }
465 }
466 SConnection::clientInit(shared);
467}
468
469void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
470{
471 SConnection::setPixelFormat(pf);
472 char buffer[256];
473 pf.print(buffer, 256);
474 vlog.info("Client pixel format %s", buffer);
475 image_getter.init(server->pb, pf, writer());
476 setCursor();
477}
478
479void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
480{
481 pointerEventTime = lastEventTime = time(0);
482 server->lastUserInputTime = lastEventTime;
483 if (!(accessRights & AccessPtrEvents)) return;
484 if (!rfb::Server::acceptPointerEvents) return;
485 if (!server->pointerClient || server->pointerClient == this) {
486 pointerEventPos = pos;
487 if (buttonMask)
488 server->pointerClient = this;
489 else
490 server->pointerClient = 0;
491 server->desktop->pointerEvent(pointerEventPos, buttonMask);
492 }
493}
494
495
496class VNCSConnectionSTShiftPresser {
497public:
498 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
499 : desktop(desktop_), pressed(false) {}
500 ~VNCSConnectionSTShiftPresser() {
501 if (pressed) { desktop->keyEvent(XK_Shift_L, false); }
502 }
503 void press() {
504 desktop->keyEvent(XK_Shift_L, true);
505 pressed = true;
506 }
507 SDesktop* desktop;
508 bool pressed;
509};
510
511// keyEvent() - record in the pressedKeys which keys were pressed. Allow
512// multiple down events (for autorepeat), but only allow a single up event.
513void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
514 lastEventTime = time(0);
515 server->lastUserInputTime = lastEventTime;
516 if (!(accessRights & AccessKeyEvents)) return;
517 if (!rfb::Server::acceptKeyEvents) return;
518
519 // Remap the key if required
520 if (server->keyRemapper)
521 key = server->keyRemapper->remapKey(key);
522
523 // Turn ISO_Left_Tab into shifted Tab.
524 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
525 if (key == XK_ISO_Left_Tab) {
526 if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
527 pressedKeys.find(XK_Shift_R) == pressedKeys.end())
528 shiftPresser.press();
529 key = XK_Tab;
530 }
531
532 if (down) {
533 pressedKeys.insert(key);
534 } else {
535 if (!pressedKeys.erase(key)) return;
536 }
537 server->desktop->keyEvent(key, down);
538}
539
540void VNCSConnectionST::clientCutText(const char* str, int len)
541{
542 if (!(accessRights & AccessCutText)) return;
543 if (!rfb::Server::acceptCutText) return;
544 server->desktop->clientCutText(str, len);
545}
546
547void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
548{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000549 Rect safeRect;
550
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000551 if (!(accessRights & AccessView)) return;
552
553 SConnection::framebufferUpdateRequest(r, incremental);
554
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000555 // Check that the client isn't sending crappy requests
556 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
557 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
558 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000559 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
560 } else {
561 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000562 }
563
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000564 // Just update the requested region.
565 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000566 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000567 if (!incremental || !continuousUpdates)
568 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000569
570 if (!incremental) {
571 // Non-incremental update - treat as if area requested has changed
572 updates.add_changed(reqRgn);
573 server->comparer->add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000574
575 // And send the screen layout to the client (which, unlike the
576 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000577 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000578
579 // We do not send a DesktopSize since it only contains the
580 // framebuffer size (which the client already should know) and
581 // because some clients don't handle extra DesktopSize events
582 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000583 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000584}
585
Pierre Ossman34bb0612009-03-21 21:16:14 +0000586void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
587 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000588{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000589 unsigned int result;
590
591 // Don't bother the desktop with an invalid configuration
592 if (!layout.validate(fb_width, fb_height)) {
593 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
594 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000595 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000596 return;
597 }
598
599 // FIXME: the desktop will call back to VNCServerST and an extra set
600 // of ExtendedDesktopSize messages will be sent. This is okay
601 // protocol-wise, but unnecessary.
602 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
603
Pierre Ossman04e62db2009-03-23 16:57:07 +0000604 writer()->writeExtendedDesktopSize(reasonClient, result,
605 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000606
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000607 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000608 if (result == resultSuccess) {
609 if (server->screenLayout != layout)
610 throw Exception("Desktop configured a different screen layout than requested");
611 server->notifyScreenLayoutChange(this);
612 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000613
614 // but always send back a reply to the requesting client
615 // (do this last as it might throw an exception on socket errors)
616 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000617}
618
Pierre Ossman2c764942011-11-14 15:54:30 +0000619void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
620{
621 if (flags & fenceFlagRequest) {
622 if (flags & fenceFlagSyncNext) {
Pierre Ossmanb8b1e962012-07-20 10:47:00 +0000623 pendingSyncFence = true;
Pierre Ossman2c764942011-11-14 15:54:30 +0000624
625 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
626 fenceDataLen = len;
627 delete [] fenceData;
628 if (len > 0) {
629 fenceData = new char[len];
630 memcpy(fenceData, data, len);
631 }
632
633 return;
634 }
635
636 // We handle everything synchronously so we trivially honor these modes
637 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
638
639 writer()->writeFence(flags, len, data);
640 return;
641 }
642
Pierre Ossman1b478e52011-11-15 12:08:30 +0000643 struct RTTInfo rttInfo;
644
Pierre Ossman2c764942011-11-14 15:54:30 +0000645 switch (len) {
646 case 0:
647 // Initial dummy fence;
648 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000649 case sizeof(struct RTTInfo):
650 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
651 handleRTTPong(rttInfo);
652 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000653 default:
654 vlog.error("Fence response of unexpected size received");
655 }
656}
657
Pierre Ossman1b478e52011-11-15 12:08:30 +0000658void VNCSConnectionST::enableContinuousUpdates(bool enable,
659 int x, int y, int w, int h)
660{
661 Rect rect;
662
663 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
664 throw Exception("Client tried to enable continuous updates when not allowed");
665
666 continuousUpdates = enable;
667
668 rect.setXYWH(x, y, w, h);
669 cuRegion.reset(rect);
670
671 if (enable) {
672 requested.clear();
673 writeFramebufferUpdate();
674 } else {
675 writer()->writeEndOfContinuousUpdates();
676 }
677}
678
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000679// supportsLocalCursor() is called whenever the status of
680// cp.supportsLocalCursor has changed. If the client does now support local
681// cursor, we make sure that the old server-side rendered cursor is cleaned up
682// and the cursor is sent to the client.
683
684void VNCSConnectionST::supportsLocalCursor()
685{
686 if (cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000687 if (!renderedCursorRect.is_empty())
688 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000689 drawRenderedCursor = false;
690 setCursor();
691 }
692}
693
Pierre Ossman2c764942011-11-14 15:54:30 +0000694void VNCSConnectionST::supportsFence()
695{
696 writer()->writeFence(fenceFlagRequest, 0, NULL);
697}
698
Pierre Ossman1b478e52011-11-15 12:08:30 +0000699void VNCSConnectionST::supportsContinuousUpdates()
700{
701 // We refuse to use continuous updates if we cannot monitor the buffer
702 // usage using fences.
703 if (!cp.supportsFence)
704 return;
705
706 writer()->writeEndOfContinuousUpdates();
707}
708
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000709void VNCSConnectionST::writeSetCursorCallback()
710{
711 if (cp.supportsLocalXCursor) {
712 Pixel pix0, pix1;
713 rdr::U8Array bitmap(server->cursor.getBitmap(&pix0, &pix1));
714 if (bitmap.buf) {
715 // The client supports XCursor and the cursor only has two
716 // colors. Use the XCursor encoding.
717 writer()->writeSetXCursor(server->cursor.width(),
718 server->cursor.height(),
719 server->cursor.hotspot.x,
720 server->cursor.hotspot.y,
721 bitmap.buf, server->cursor.mask.buf);
722 return;
723 } else {
724 // More than two colors
725 if (!cp.supportsLocalCursor) {
726 // FIXME: We could reduce to two colors.
727 vlog.info("Unable to send multicolor cursor: RichCursor not supported by client");
728 return;
729 }
730 }
731 }
732
733 // Use RichCursor
734 rdr::U8* transData = writer()->getImageBuf(server->cursor.area());
735 image_getter.translatePixels(server->cursor.data, transData,
736 server->cursor.area());
737 writer()->writeSetCursor(server->cursor.width(),
738 server->cursor.height(),
739 server->cursor.hotspot,
740 transData, server->cursor.mask.buf);
741}
742
743
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000744bool VNCSConnectionST::handleTimeout(Timer* t)
745{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000746 try {
747 if (t == &updateTimer)
748 writeFramebufferUpdate();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000749 else if (t == &congestionTimer)
750 updateCongestion();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000751 } catch (rdr::Exception& e) {
752 close(e.str());
753 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000754
755 return false;
756}
757
758
Pierre Ossman1b478e52011-11-15 12:08:30 +0000759void VNCSConnectionST::writeRTTPing()
760{
761 struct RTTInfo rttInfo;
762
763 if (!cp.supportsFence)
764 return;
765
766 memset(&rttInfo, 0, sizeof(struct RTTInfo));
767
768 gettimeofday(&rttInfo.tv, NULL);
769 rttInfo.offset = sock->outStream().length();
770 rttInfo.inFlight = rttInfo.offset - ackedOffset;
771
772 // We need to make sure any old update are already processed by the
773 // time we get the response back. This allows us to reliably throttle
774 // back on client overload, as well as network overload.
775 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
776 sizeof(struct RTTInfo), (const char*)&rttInfo);
777
778 pingCounter++;
779
780 sentOffset = rttInfo.offset;
781
782 // Let some data flow before we adjust the settings
783 if (!congestionTimer.isStarted())
784 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
785}
786
787void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
788{
789 unsigned rtt, delay;
790 int bdp;
791
792 pingCounter--;
793
794 rtt = msSince(&rttInfo.tv);
795 if (rtt < 1)
796 rtt = 1;
797
798 ackedOffset = rttInfo.offset;
799
800 // Try to estimate wire latency by tracking lowest seen latency
801 if (rtt < baseRTT)
802 baseRTT = rtt;
803
804 if (rttInfo.inFlight > congWindow) {
805 seenCongestion = true;
806
807 // Estimate added delay because of overtaxed buffers
808 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
809
810 if (delay < rtt)
811 rtt -= delay;
812 else
813 rtt = 1;
814
815 // If we underestimate the congestion window, then we'll get a latency
816 // that's less than the wire latency, which will confuse other portions
817 // of the code.
818 if (rtt < baseRTT)
819 rtt = baseRTT;
820 }
821
822 // We only keep track of the minimum latency seen (for a given interval)
823 // on the basis that we want to avoid continous buffer issue, but don't
824 // mind (or even approve of) bursts.
825 if (rtt < minRTT)
826 minRTT = rtt;
827}
828
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000829bool VNCSConnectionST::isCongested()
830{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000831 int offset;
832
833 // Stuff still waiting in the send buffer?
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000834 if (sock->outStream().bufferUsage() > 0)
835 return true;
836
Pierre Ossman1b478e52011-11-15 12:08:30 +0000837 if (!cp.supportsFence)
838 return false;
839
840 // Idle for too long? (and no data on the wire)
841 //
842 // FIXME: This should really just be one baseRTT, but we're getting
843 // problems with triggering the idle timeout on each update.
844 // Maybe we need to use a moving average for the wire latency
845 // instead of baseRTT.
846 if ((sentOffset == ackedOffset) &&
847 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
848
849#ifdef CONGESTION_DEBUG
850 if (congWindow > INITIAL_WINDOW)
851 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
852 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
853#endif
854
855 // Close congestion window and allow a transfer
856 // FIXME: Reset baseRTT like Linux Vegas?
857 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
858
859 return false;
860 }
861
862 offset = sock->outStream().length();
863
864 // FIXME: Should we compensate for non-update data?
865 // (i.e. use sentOffset instead of offset)
866 if ((offset - ackedOffset) < congWindow)
867 return false;
868
869 // If we just have one outstanding "ping", that means the client has
870 // started receiving our update. In order to not regress compared to
871 // before we had congestion avoidance, we allow another update here.
872 // This could further clog up the tubes, but congestion control isn't
873 // really working properly right now anyway as the wire would otherwise
874 // be idle for at least RTT/2.
875 if (pingCounter == 1)
876 return false;
877
878 return true;
879}
880
881
882void VNCSConnectionST::updateCongestion()
883{
884 unsigned diff;
885
886 if (!seenCongestion)
887 return;
888
889 diff = minRTT - baseRTT;
890
891 if (diff > __rfbmin(100, baseRTT)) {
892 // Way too fast
893 congWindow = congWindow * baseRTT / minRTT;
894 } else if (diff > __rfbmin(50, baseRTT/2)) {
895 // Slightly too fast
896 congWindow -= 4096;
897 } else if (diff < 5) {
898 // Way too slow
899 congWindow += 8192;
900 } else if (diff < 25) {
901 // Too slow
902 congWindow += 4096;
903 }
904
905 if (congWindow < MINIMUM_WINDOW)
906 congWindow = MINIMUM_WINDOW;
907 if (congWindow > MAXIMUM_WINDOW)
908 congWindow = MAXIMUM_WINDOW;
909
910#ifdef CONGESTION_DEBUG
911 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
912 minRTT, baseRTT, congWindow / 1024,
913 congWindow * 8.0 / baseRTT / 1000.0);
914
915#ifdef TCP_INFO
916 struct tcp_info tcp_info;
917 socklen_t tcp_info_length;
918
919 tcp_info_length = sizeof(tcp_info);
920 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
921 (void *)&tcp_info, &tcp_info_length) == 0) {
922 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
923 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
924 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
925 }
926#endif
927
928#endif
929
930 minRTT = -1;
931 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000932}
933
934
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000935void VNCSConnectionST::writeFramebufferUpdate()
936{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000937 Region req;
938 UpdateInfo ui;
939 bool needNewUpdateInfo;
940
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000941 updateTimer.stop();
942
Pierre Ossman2c764942011-11-14 15:54:30 +0000943 // We're in the middle of processing a command that's supposed to be
944 // synchronised. Allowing an update to slip out right now might violate
945 // that synchronisation.
946 if (syncFence)
947 return;
948
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000949 // We try to aggregate responses, so don't send out anything whilst we
950 // still have incoming messages. processMessages() will give us another
951 // chance to run once things are idle.
952 if (inProcessMessages)
953 return;
954
Pierre Ossman1b478e52011-11-15 12:08:30 +0000955 if (state() != RFBSTATE_NORMAL)
956 return;
957 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000958 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000959
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000960 // Check that we actually have some space on the link and retry in a
961 // bit if things are congested.
962 if (isCongested()) {
963 updateTimer.start(50);
964 return;
965 }
966
Pierre Ossman36dadf82011-11-15 12:11:32 +0000967 // In continuous mode, we will be outputting at least three distinct
968 // messages. We need to aggregate these in order to not clog up TCP's
969 // congestion window.
970 network::TcpSocket::cork(sock->getFd(), true);
971
Pierre Ossmane9962f72009-04-23 12:31:42 +0000972 // First take care of any updates that cannot contain framebuffer data
973 // changes.
974 if (writer()->needNoDataUpdate()) {
975 writer()->writeNoDataUpdate();
976 requested.clear();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000977 if (!continuousUpdates)
Pierre Ossman36dadf82011-11-15 12:11:32 +0000978 goto out;
Pierre Ossmane9962f72009-04-23 12:31:42 +0000979 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000980
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000981 updates.enable_copyrect(cp.useCopyRect);
982
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000983 // Fetch updates from server object, and see if we are allowed to send
984 // anything right now (the framebuffer might have changed in ways we
985 // haven't yet been informed of).
986 if (!server->checkUpdate())
Pierre Ossman36dadf82011-11-15 12:11:32 +0000987 goto out;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +0000988
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000989 // Get the lists of updates. Prior to exporting the data to the `ui' object,
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000990 // getUpdateInfo() will normalize the `updates' object such way that its
Pierre Ossman02e43d72009-03-05 11:57:11 +0000991 // `changed' and `copied' regions would not intersect.
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000992
Pierre Ossman1b478e52011-11-15 12:08:30 +0000993 if (continuousUpdates)
994 req = cuRegion.union_(requested);
995 else
996 req = requested;
997
998 updates.getUpdateInfo(&ui, req);
999 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001000
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001001 // If the previous position of the rendered cursor overlaps the source of the
1002 // copy, then when the copy happens the corresponding rectangle in the
1003 // destination will be wrong, so add it to the changed region.
1004
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001005 if (!ui.copied.is_empty() && !renderedCursorRect.is_empty()) {
1006 Rect bogusCopiedCursor = (renderedCursorRect.translate(ui.copy_delta)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001007 .intersect(server->pb->getRect()));
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001008 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001009 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001010 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001011 }
1012 }
1013
1014 // If we need to remove the old rendered cursor, just add the rectangle to
1015 // the changed region.
1016
1017 if (removeRenderedCursor) {
1018 updates.add_changed(renderedCursorRect);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001019 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001020 renderedCursorRect.clear();
1021 removeRenderedCursor = false;
1022 }
1023
1024 // Return if there is nothing to send the client.
1025
1026 if (updates.is_empty() && !writer()->needFakeUpdate() && !drawRenderedCursor)
Pierre Ossman36dadf82011-11-15 12:11:32 +00001027 goto out;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001028
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001029 // The `updates' object could change, make sure we have valid update info.
1030
1031 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001032 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001033
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001034 // If the client needs a server-side rendered cursor, work out the cursor
1035 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1036 // with the update region, we need to draw the rendered cursor regardless of
1037 // whether it has changed.
1038
1039 if (needRenderedCursor()) {
1040 renderedCursorRect
1041 = (server->renderedCursor.getRect(server->renderedCursorTL)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001042 .intersect(req.get_bounding_rect()));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001043
1044 if (renderedCursorRect.is_empty()) {
1045 drawRenderedCursor = false;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001046 } else if (!ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001047 .intersect(renderedCursorRect).is_empty()) {
1048 drawRenderedCursor = true;
1049 }
1050
1051 // We could remove the new cursor rect from updates here. It's not clear
1052 // whether this is worth it. If we do remove it, then we won't draw over
1053 // the same bit of screen twice, but we have the overhead of a more complex
1054 // region.
1055
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001056 //if (drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001057 // updates.subtract(renderedCursorRect);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001058 // updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001059 //}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001060 }
1061
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001062 if (!ui.is_empty() || writer()->needFakeUpdate() || drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001063 // Compute the number of rectangles. Tight encoder makes the things more
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001064 // complicated as compared to the original VNC4.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001065 writer()->setupCurrentEncoder();
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +00001066 int nRects = (ui.copied.numRects() +
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +00001067 (drawRenderedCursor ? 1 : 0));
Constantin Kaplinsky651606d2007-10-17 17:40:23 +00001068
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001069 std::vector<Rect> rects;
1070 std::vector<Rect>::const_iterator i;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001071 ui.changed.get_rects(&rects);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001072 for (i = rects.begin(); i != rects.end(); i++) {
DRCcd2c5d42011-08-11 11:18:34 +00001073 if (i->width() && i->height()) {
1074 int nUpdateRects = writer()->getNumRects(*i);
1075 if (nUpdateRects == 0 && cp.currentEncoding() == encodingTight) {
Pierre Ossman65fb4b02012-02-28 11:54:01 +00001076 // With Tight encoding and LastRect support, the client does not
1077 // care about the number of rectangles in the update - it will
1078 // stop parsing when it encounters a LastRect "rectangle".
1079 // In this case, pretend to send 65535 rectangles.
DRCcd2c5d42011-08-11 11:18:34 +00001080 nRects = 0xFFFF; break;
1081 }
1082 else
1083 nRects += nUpdateRects;
1084 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001085 }
Pierre Ossman1b478e52011-11-15 12:08:30 +00001086
1087 writeRTTPing();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001088
1089 writer()->writeFramebufferUpdateStart(nRects);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001090
Pierre Ossman717c07b2014-01-21 14:45:10 +01001091 writer()->writeRects(ui, &image_getter);
1092 updates.clear();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001093
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001094 if (drawRenderedCursor)
1095 writeRenderedCursorRect();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001096
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001097 writer()->writeFramebufferUpdateEnd();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001098
1099 writeRTTPing();
1100
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001101 requested.clear();
1102 }
Pierre Ossman36dadf82011-11-15 12:11:32 +00001103
1104out:
1105 network::TcpSocket::cork(sock->getFd(), false);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001106}
1107
1108
1109// writeRenderedCursorRect() writes a single rectangle drawing the rendered
1110// cursor on the client.
1111
1112void VNCSConnectionST::writeRenderedCursorRect()
1113{
1114 image_getter.setPixelBuffer(&server->renderedCursor);
1115 image_getter.setOffset(server->renderedCursorTL);
1116
Pierre Ossman717c07b2014-01-21 14:45:10 +01001117 writer()->writeRect(renderedCursorRect, &image_getter);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001118
1119 image_getter.setPixelBuffer(server->pb);
1120 image_getter.setOffset(Point(0,0));
1121
1122 drawRenderedCursor = false;
1123}
1124
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001125void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1126{
1127 if (!authenticated())
1128 return;
1129
1130 cp.screenLayout = server->screenLayout;
1131
1132 if (state() != RFBSTATE_NORMAL)
1133 return;
1134
1135 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1136 cp.screenLayout);
1137 writeFramebufferUpdate();
1138}
1139
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001140
1141// setCursor() is called whenever the cursor has changed shape or pixel format.
1142// If the client supports local cursor then it will arrange for the cursor to
1143// be sent to the client.
1144
1145void VNCSConnectionST::setCursor()
1146{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001147 if (state() != RFBSTATE_NORMAL)
1148 return;
1149 if (!cp.supportsLocalCursor)
1150 return;
1151
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001152 writer()->cursorChange(this);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001153 writeFramebufferUpdate();
1154}
1155
1156void VNCSConnectionST::setDesktopName(const char *name)
1157{
1158 cp.setName(name);
1159
1160 if (state() != RFBSTATE_NORMAL)
1161 return;
1162
1163 if (!writer()->writeSetDesktopName()) {
1164 fprintf(stderr, "Client does not support desktop rename\n");
1165 return;
1166 }
1167
1168 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001169}
1170
1171void VNCSConnectionST::setSocketTimeouts()
1172{
1173 int timeoutms = rfb::Server::clientWaitTimeMillis;
1174 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1175 if (timeoutms == 0)
1176 timeoutms = -1;
1177 sock->inStream().setTimeout(timeoutms);
1178 sock->outStream().setTimeout(timeoutms);
1179}
1180
1181char* VNCSConnectionST::getStartTime()
1182{
1183 char* result = ctime(&startTime);
1184 result[24] = '\0';
1185 return result;
1186}
1187
1188void VNCSConnectionST::setStatus(int status)
1189{
1190 switch (status) {
1191 case 0:
1192 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1193 break;
1194 case 1:
Adam Tkac8e985062011-02-07 11:33:57 +00001195 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001196 break;
1197 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001198 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001199 break;
1200 }
1201 framebufferUpdateRequest(server->pb->getRect(), false);
1202}
1203int VNCSConnectionST::getStatus()
1204{
1205 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1206 return 0;
1207 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1208 return 1;
1209 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1210 return 2;
1211 return 4;
1212}
1213