blob: bd93d633ce5c0529d8fa004e3d3bca8309bd6052 [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),
69 syncFence(false), fenceFlags(0), fenceDataLen(0), fenceData(NULL),
Pierre Ossman1b478e52011-11-15 12:08:30 +000070 baseRTT(-1), minRTT(-1), seenCongestion(false), pingCounter(0),
71 ackedOffset(0), sentOffset(0), congWindow(0), congestionTimer(this),
Pierre Ossman2c764942011-11-14 15:54:30 +000072 server(server_),
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000073 updates(false), image_getter(server->useEconomicTranslate),
74 drawRenderedCursor(false), removeRenderedCursor(false),
Pierre Ossman1b478e52011-11-15 12:08:30 +000075 continuousUpdates(false),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000076 updateTimer(this), pointerEventTime(0),
77 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000078{
79 setStreams(&sock->inStream(), &sock->outStream());
80 peerEndpoint.buf = sock->getPeerEndpoint();
81 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
82
83 // Configure the socket
84 setSocketTimeouts();
85 lastEventTime = time(0);
86
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000087 server->clients.push_front(this);
88}
89
90
91VNCSConnectionST::~VNCSConnectionST()
92{
93 // If we reach here then VNCServerST is deleting us!
94 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
95 peerEndpoint.buf,
96 (closeReason.buf) ? closeReason.buf : "");
97
98 // Release any keys the client still had pressed
99 std::set<rdr::U32>::iterator i;
100 for (i=pressedKeys.begin(); i!=pressedKeys.end(); i++)
101 server->desktop->keyEvent(*i, false);
102 if (server->pointerClient == this)
103 server->pointerClient = 0;
104
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000105 // Remove this client from the server
106 server->clients.remove(this);
107
Pierre Ossman2c764942011-11-14 15:54:30 +0000108 delete [] fenceData;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000109}
110
111
112// Methods called from VNCServerST
113
114bool VNCSConnectionST::init()
115{
116 try {
117 initialiseProtocol();
118 } catch (rdr::Exception& e) {
119 close(e.str());
120 return false;
121 }
122 return true;
123}
124
125void VNCSConnectionST::close(const char* reason)
126{
127 // Log the reason for the close
128 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +0000129 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000130 else
131 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
132
133 if (authenticated()) {
134 server->lastDisconnectTime = time(0);
135 }
136
137 // Just shutdown the socket and mark our state as closing. Eventually the
138 // calling code will call VNCServerST's removeSocket() method causing us to
139 // be deleted.
140 sock->shutdown();
141 setState(RFBSTATE_CLOSING);
142}
143
144
145void VNCSConnectionST::processMessages()
146{
147 if (state() == RFBSTATE_CLOSING) return;
148 try {
149 // - Now set appropriate socket timeouts and process data
150 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000151
152 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000153
Pierre Ossmana830bec2011-11-08 12:12:02 +0000154 // Get the underlying TCP layer to build large packets if we send
155 // multiple small responses.
156 network::TcpSocket::cork(sock->getFd(), true);
157
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000158 while (getInStream()->checkNoWait(1)) {
159 processMsg();
Pierre Ossman2c764942011-11-14 15:54:30 +0000160 if (syncFence) {
161 writer()->writeFence(fenceFlags, fenceDataLen, fenceData);
162 syncFence = false;
163 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000164 }
165
Pierre Ossmana830bec2011-11-08 12:12:02 +0000166 // Flush out everything in case we go idle after this.
167 network::TcpSocket::cork(sock->getFd(), false);
168
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000169 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000170
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000171 // If there were anything requiring an update, try to send it here.
172 // We wait until now with this to aggregate responses and to give
173 // higher priority to user actions such as keyboard and pointer events.
174 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000175 } catch (rdr::EndOfStream&) {
176 close("Clean disconnection");
177 } catch (rdr::Exception &e) {
178 close(e.str());
179 }
180}
181
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000182void VNCSConnectionST::pixelBufferChange()
183{
184 try {
185 if (!authenticated()) return;
186 if (cp.width && cp.height && (server->pb->width() != cp.width ||
187 server->pb->height() != cp.height))
188 {
189 // We need to clip the next update to the new size, but also add any
190 // extra bits if it's bigger. If we wanted to do this exactly, something
191 // like the code below would do it, but at the moment we just update the
192 // entire new size. However, we do need to clip the renderedCursorRect
193 // because that might be added to updates in writeFramebufferUpdate().
194
195 //updates.intersect(server->pb->getRect());
196 //
197 //if (server->pb->width() > cp.width)
198 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
199 // server->pb->height()));
200 //if (server->pb->height() > cp.height)
201 // updates.add_changed(Rect(0, cp.height, cp.width,
202 // server->pb->height()));
203
204 renderedCursorRect = renderedCursorRect.intersect(server->pb->getRect());
205
206 cp.width = server->pb->width();
207 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000208 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000209 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000210 // We should only send EDS to client asking for both
211 if (!writer()->writeExtendedDesktopSize()) {
212 if (!writer()->writeSetDesktopSize()) {
213 close("Client does not support desktop resize");
214 return;
215 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000216 }
217 }
218 }
219 // Just update the whole screen at the moment because we're too lazy to
220 // work out what's actually changed.
221 updates.clear();
222 updates.add_changed(server->pb->getRect());
223 vlog.debug("pixel buffer changed - re-initialising image getter");
224 image_getter.init(server->pb, cp.pf(), writer());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000225 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000226 } catch(rdr::Exception &e) {
227 close(e.str());
228 }
229}
230
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000231void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000232{
233 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000234 writeFramebufferUpdate();
235 } catch(rdr::Exception &e) {
236 close(e.str());
237 }
238}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000239
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000240void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
241{
242 try {
243 screenLayoutChange(reason);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000244 } catch(rdr::Exception &e) {
245 close(e.str());
246 }
247}
248
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000249void VNCSConnectionST::setColourMapEntriesOrClose(int firstColour,int nColours)
250{
251 try {
252 setColourMapEntries(firstColour, nColours);
253 } catch(rdr::Exception& e) {
254 close(e.str());
255 }
256}
257
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000258void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000259{
260 try {
261 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
262 } catch(rdr::Exception& e) {
263 close(e.str());
264 }
265}
266
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000267void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000268{
269 try {
270 if (!(accessRights & AccessCutText)) return;
271 if (!rfb::Server::sendCutText) return;
272 if (state() == RFBSTATE_NORMAL)
273 writer()->writeServerCutText(str, len);
274 } catch(rdr::Exception& e) {
275 close(e.str());
276 }
277}
278
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000279
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000280void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000281{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000282 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000283 setDesktopName(name);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000284 } catch(rdr::Exception& e) {
285 close(e.str());
286 }
287}
288
289
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000290void VNCSConnectionST::setCursorOrClose()
291{
292 try {
293 setCursor();
294 } catch(rdr::Exception& e) {
295 close(e.str());
296 }
297}
298
299
300int VNCSConnectionST::checkIdleTimeout()
301{
302 int idleTimeout = rfb::Server::idleTimeout;
303 if (idleTimeout == 0) return 0;
304 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
305 idleTimeout = 15; // minimum of 15 seconds while authenticating
306 time_t now = time(0);
307 if (now < lastEventTime) {
308 // Someone must have set the time backwards. Set lastEventTime so that the
309 // idleTimeout will count from now.
310 vlog.info("Time has gone backwards - resetting idle timeout");
311 lastEventTime = now;
312 }
313 int timeLeft = lastEventTime + idleTimeout - now;
314 if (timeLeft < -60) {
315 // Our callback is over a minute late - someone must have set the time
316 // forwards. Set lastEventTime so that the idleTimeout will count from
317 // now.
318 vlog.info("Time has gone forwards - resetting idle timeout");
319 lastEventTime = now;
320 return secsToMillis(idleTimeout);
321 }
322 if (timeLeft <= 0) {
323 close("Idle timeout");
324 return 0;
325 }
326 return secsToMillis(timeLeft);
327}
328
329// renderedCursorChange() is called whenever the server-side rendered cursor
330// changes shape or position. It ensures that the next update will clean up
331// the old rendered cursor and if necessary draw the new rendered cursor.
332
333void VNCSConnectionST::renderedCursorChange()
334{
335 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000336 if (!renderedCursorRect.is_empty())
337 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000338 if (needRenderedCursor())
339 drawRenderedCursor = true;
340}
341
342// needRenderedCursor() returns true if this client needs the server-side
343// rendered cursor. This may be because it does not support local cursor or
344// because the current cursor position has not been set by this client.
345// Unfortunately we can't know for sure when the current cursor position has
346// been set by this client. We guess that this is the case when the current
347// cursor position is the same as the last pointer event from this client, or
348// if it is a very short time since this client's last pointer event (up to a
349// second). [ Ideally we should do finer-grained timing here and make the time
350// configurable, but I don't think it's that important. ]
351
352bool VNCSConnectionST::needRenderedCursor()
353{
Peter Ã…strandffeeb262010-02-10 09:29:00 +0000354 bool pointerpos = (!server->cursorPos.equals(pointerEventPos) && (time(0) - pointerEventTime) > 0);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000355 return (state() == RFBSTATE_NORMAL
Peter Ã…strandffeeb262010-02-10 09:29:00 +0000356 && ((!cp.supportsLocalCursor && !cp.supportsLocalXCursor) || pointerpos));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000357}
358
359
360void VNCSConnectionST::approveConnectionOrClose(bool accept,
361 const char* reason)
362{
363 try {
364 approveConnection(accept, reason);
365 } catch (rdr::Exception& e) {
366 close(e.str());
367 }
368}
369
370
371
372// -=- Callbacks from SConnection
373
374void VNCSConnectionST::authSuccess()
375{
376 lastEventTime = time(0);
377
378 server->startDesktop();
379
380 // - Set the connection parameters appropriately
381 cp.width = server->pb->width();
382 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000383 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000384 cp.setName(server->getName());
385
386 // - Set the default pixel format
387 cp.setPF(server->pb->getPF());
388 char buffer[256];
389 cp.pf().print(buffer, 256);
390 vlog.info("Server default pixel format %s", buffer);
391 image_getter.init(server->pb, cp.pf(), 0);
392
393 // - Mark the entire display as "dirty"
394 updates.add_changed(server->pb->getRect());
395 startTime = time(0);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000396
397 // - Bootstrap the congestion control
398 ackedOffset = sock->outStream().length();
399 congWindow = INITIAL_WINDOW;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000400}
401
402void VNCSConnectionST::queryConnection(const char* userName)
403{
404 // - Authentication succeeded - clear from blacklist
405 CharArray name; name.buf = sock->getPeerAddress();
406 server->blHosts->clearBlackmark(name.buf);
407
408 // - Special case to provide a more useful error message
409 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
410 server->authClientCount() > 0) {
411 approveConnection(false, "The server is already in use");
412 return;
413 }
414
415 // - Does the client have the right to bypass the query?
416 if (reverseConnection ||
417 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
418 (accessRights & AccessNoQuery))
419 {
420 approveConnection(true);
421 return;
422 }
423
424 // - Get the server to display an Accept/Reject dialog, if required
425 // If a dialog is displayed, the result will be PENDING, and the
426 // server will call approveConnection at a later time
427 CharArray reason;
428 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
429 &reason.buf);
430 if (qr == VNCServerST::PENDING)
431 return;
432
433 // - If server returns ACCEPT/REJECT then pass result to SConnection
434 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
435}
436
437void VNCSConnectionST::clientInit(bool shared)
438{
439 lastEventTime = time(0);
440 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
441 if (rfb::Server::neverShared) shared = false;
442 if (!shared) {
443 if (rfb::Server::disconnectClients) {
444 // - Close all the other connected clients
445 vlog.debug("non-shared connection - closing clients");
446 server->closeClients("Non-shared connection requested", getSock());
447 } else {
448 // - Refuse this connection if there are existing clients, in addition to
449 // this one
450 if (server->authClientCount() > 1) {
451 close("Server is already in use");
452 return;
453 }
454 }
455 }
456 SConnection::clientInit(shared);
457}
458
459void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
460{
461 SConnection::setPixelFormat(pf);
462 char buffer[256];
463 pf.print(buffer, 256);
464 vlog.info("Client pixel format %s", buffer);
465 image_getter.init(server->pb, pf, writer());
466 setCursor();
467}
468
469void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
470{
471 pointerEventTime = lastEventTime = time(0);
472 server->lastUserInputTime = lastEventTime;
473 if (!(accessRights & AccessPtrEvents)) return;
474 if (!rfb::Server::acceptPointerEvents) return;
475 if (!server->pointerClient || server->pointerClient == this) {
476 pointerEventPos = pos;
477 if (buttonMask)
478 server->pointerClient = this;
479 else
480 server->pointerClient = 0;
481 server->desktop->pointerEvent(pointerEventPos, buttonMask);
482 }
483}
484
485
486class VNCSConnectionSTShiftPresser {
487public:
488 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
489 : desktop(desktop_), pressed(false) {}
490 ~VNCSConnectionSTShiftPresser() {
491 if (pressed) { desktop->keyEvent(XK_Shift_L, false); }
492 }
493 void press() {
494 desktop->keyEvent(XK_Shift_L, true);
495 pressed = true;
496 }
497 SDesktop* desktop;
498 bool pressed;
499};
500
501// keyEvent() - record in the pressedKeys which keys were pressed. Allow
502// multiple down events (for autorepeat), but only allow a single up event.
503void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
504 lastEventTime = time(0);
505 server->lastUserInputTime = lastEventTime;
506 if (!(accessRights & AccessKeyEvents)) return;
507 if (!rfb::Server::acceptKeyEvents) return;
508
509 // Remap the key if required
510 if (server->keyRemapper)
511 key = server->keyRemapper->remapKey(key);
512
513 // Turn ISO_Left_Tab into shifted Tab.
514 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
515 if (key == XK_ISO_Left_Tab) {
516 if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
517 pressedKeys.find(XK_Shift_R) == pressedKeys.end())
518 shiftPresser.press();
519 key = XK_Tab;
520 }
521
522 if (down) {
523 pressedKeys.insert(key);
524 } else {
525 if (!pressedKeys.erase(key)) return;
526 }
527 server->desktop->keyEvent(key, down);
528}
529
530void VNCSConnectionST::clientCutText(const char* str, int len)
531{
532 if (!(accessRights & AccessCutText)) return;
533 if (!rfb::Server::acceptCutText) return;
534 server->desktop->clientCutText(str, len);
535}
536
537void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
538{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000539 Rect safeRect;
540
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000541 if (!(accessRights & AccessView)) return;
542
543 SConnection::framebufferUpdateRequest(r, incremental);
544
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000545 // Check that the client isn't sending crappy requests
546 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
547 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
548 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000549 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
550 } else {
551 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000552 }
553
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000554 // Just update the requested region.
555 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000556 Region reqRgn(r);
Pierre Ossman1b478e52011-11-15 12:08:30 +0000557 if (!incremental || !continuousUpdates)
558 requested.assign_union(reqRgn);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000559
560 if (!incremental) {
561 // Non-incremental update - treat as if area requested has changed
562 updates.add_changed(reqRgn);
563 server->comparer->add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000564
565 // And send the screen layout to the client (which, unlike the
566 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000567 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000568
569 // We do not send a DesktopSize since it only contains the
570 // framebuffer size (which the client already should know) and
571 // because some clients don't handle extra DesktopSize events
572 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000573 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000574}
575
Pierre Ossman34bb0612009-03-21 21:16:14 +0000576void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
577 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000578{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000579 unsigned int result;
580
581 // Don't bother the desktop with an invalid configuration
582 if (!layout.validate(fb_width, fb_height)) {
583 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
584 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000585 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000586 return;
587 }
588
589 // FIXME: the desktop will call back to VNCServerST and an extra set
590 // of ExtendedDesktopSize messages will be sent. This is okay
591 // protocol-wise, but unnecessary.
592 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
593
Pierre Ossman04e62db2009-03-23 16:57:07 +0000594 writer()->writeExtendedDesktopSize(reasonClient, result,
595 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000596
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000597 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000598 if (result == resultSuccess) {
599 if (server->screenLayout != layout)
600 throw Exception("Desktop configured a different screen layout than requested");
601 server->notifyScreenLayoutChange(this);
602 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000603
604 // but always send back a reply to the requesting client
605 // (do this last as it might throw an exception on socket errors)
606 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000607}
608
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000609void VNCSConnectionST::setInitialColourMap()
610{
611 setColourMapEntries(0, 0);
612}
613
Pierre Ossman2c764942011-11-14 15:54:30 +0000614void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
615{
616 if (flags & fenceFlagRequest) {
617 if (flags & fenceFlagSyncNext) {
618 if (syncFence)
619 vlog.error("Fence trying to synchronise another fence");
620
621 syncFence = true;
622
623 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
624 fenceDataLen = len;
625 delete [] fenceData;
626 if (len > 0) {
627 fenceData = new char[len];
628 memcpy(fenceData, data, len);
629 }
630
631 return;
632 }
633
634 // We handle everything synchronously so we trivially honor these modes
635 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
636
637 writer()->writeFence(flags, len, data);
638 return;
639 }
640
Pierre Ossman1b478e52011-11-15 12:08:30 +0000641 struct RTTInfo rttInfo;
642
Pierre Ossman2c764942011-11-14 15:54:30 +0000643 switch (len) {
644 case 0:
645 // Initial dummy fence;
646 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000647 case sizeof(struct RTTInfo):
648 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
649 handleRTTPong(rttInfo);
650 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000651 default:
652 vlog.error("Fence response of unexpected size received");
653 }
654}
655
Pierre Ossman1b478e52011-11-15 12:08:30 +0000656void VNCSConnectionST::enableContinuousUpdates(bool enable,
657 int x, int y, int w, int h)
658{
659 Rect rect;
660
661 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
662 throw Exception("Client tried to enable continuous updates when not allowed");
663
664 continuousUpdates = enable;
665
666 rect.setXYWH(x, y, w, h);
667 cuRegion.reset(rect);
668
669 if (enable) {
670 requested.clear();
671 writeFramebufferUpdate();
672 } else {
673 writer()->writeEndOfContinuousUpdates();
674 }
675}
676
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000677// supportsLocalCursor() is called whenever the status of
678// cp.supportsLocalCursor has changed. If the client does now support local
679// cursor, we make sure that the old server-side rendered cursor is cleaned up
680// and the cursor is sent to the client.
681
682void VNCSConnectionST::supportsLocalCursor()
683{
684 if (cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000685 if (!renderedCursorRect.is_empty())
686 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000687 drawRenderedCursor = false;
688 setCursor();
689 }
690}
691
Pierre Ossman2c764942011-11-14 15:54:30 +0000692void VNCSConnectionST::supportsFence()
693{
694 writer()->writeFence(fenceFlagRequest, 0, NULL);
695}
696
Pierre Ossman1b478e52011-11-15 12:08:30 +0000697void VNCSConnectionST::supportsContinuousUpdates()
698{
699 // We refuse to use continuous updates if we cannot monitor the buffer
700 // usage using fences.
701 if (!cp.supportsFence)
702 return;
703
704 writer()->writeEndOfContinuousUpdates();
705}
706
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000707void VNCSConnectionST::writeSetCursorCallback()
708{
709 if (cp.supportsLocalXCursor) {
710 Pixel pix0, pix1;
711 rdr::U8Array bitmap(server->cursor.getBitmap(&pix0, &pix1));
712 if (bitmap.buf) {
713 // The client supports XCursor and the cursor only has two
714 // colors. Use the XCursor encoding.
715 writer()->writeSetXCursor(server->cursor.width(),
716 server->cursor.height(),
717 server->cursor.hotspot.x,
718 server->cursor.hotspot.y,
719 bitmap.buf, server->cursor.mask.buf);
720 return;
721 } else {
722 // More than two colors
723 if (!cp.supportsLocalCursor) {
724 // FIXME: We could reduce to two colors.
725 vlog.info("Unable to send multicolor cursor: RichCursor not supported by client");
726 return;
727 }
728 }
729 }
730
731 // Use RichCursor
732 rdr::U8* transData = writer()->getImageBuf(server->cursor.area());
733 image_getter.translatePixels(server->cursor.data, transData,
734 server->cursor.area());
735 writer()->writeSetCursor(server->cursor.width(),
736 server->cursor.height(),
737 server->cursor.hotspot,
738 transData, server->cursor.mask.buf);
739}
740
741
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000742bool VNCSConnectionST::handleTimeout(Timer* t)
743{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000744 try {
745 if (t == &updateTimer)
746 writeFramebufferUpdate();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000747 else if (t == &congestionTimer)
748 updateCongestion();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000749 } catch (rdr::Exception& e) {
750 close(e.str());
751 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000752
753 return false;
754}
755
756
Pierre Ossman1b478e52011-11-15 12:08:30 +0000757void VNCSConnectionST::writeRTTPing()
758{
759 struct RTTInfo rttInfo;
760
761 if (!cp.supportsFence)
762 return;
763
764 memset(&rttInfo, 0, sizeof(struct RTTInfo));
765
766 gettimeofday(&rttInfo.tv, NULL);
767 rttInfo.offset = sock->outStream().length();
768 rttInfo.inFlight = rttInfo.offset - ackedOffset;
769
770 // We need to make sure any old update are already processed by the
771 // time we get the response back. This allows us to reliably throttle
772 // back on client overload, as well as network overload.
773 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
774 sizeof(struct RTTInfo), (const char*)&rttInfo);
775
776 pingCounter++;
777
778 sentOffset = rttInfo.offset;
779
780 // Let some data flow before we adjust the settings
781 if (!congestionTimer.isStarted())
782 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
783}
784
785void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
786{
787 unsigned rtt, delay;
788 int bdp;
789
790 pingCounter--;
791
792 rtt = msSince(&rttInfo.tv);
793 if (rtt < 1)
794 rtt = 1;
795
796 ackedOffset = rttInfo.offset;
797
798 // Try to estimate wire latency by tracking lowest seen latency
799 if (rtt < baseRTT)
800 baseRTT = rtt;
801
802 if (rttInfo.inFlight > congWindow) {
803 seenCongestion = true;
804
805 // Estimate added delay because of overtaxed buffers
806 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
807
808 if (delay < rtt)
809 rtt -= delay;
810 else
811 rtt = 1;
812
813 // If we underestimate the congestion window, then we'll get a latency
814 // that's less than the wire latency, which will confuse other portions
815 // of the code.
816 if (rtt < baseRTT)
817 rtt = baseRTT;
818 }
819
820 // We only keep track of the minimum latency seen (for a given interval)
821 // on the basis that we want to avoid continous buffer issue, but don't
822 // mind (or even approve of) bursts.
823 if (rtt < minRTT)
824 minRTT = rtt;
825}
826
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000827bool VNCSConnectionST::isCongested()
828{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000829 int offset;
830
831 // Stuff still waiting in the send buffer?
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000832 if (sock->outStream().bufferUsage() > 0)
833 return true;
834
Pierre Ossman1b478e52011-11-15 12:08:30 +0000835 if (!cp.supportsFence)
836 return false;
837
838 // Idle for too long? (and no data on the wire)
839 //
840 // FIXME: This should really just be one baseRTT, but we're getting
841 // problems with triggering the idle timeout on each update.
842 // Maybe we need to use a moving average for the wire latency
843 // instead of baseRTT.
844 if ((sentOffset == ackedOffset) &&
845 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
846
847#ifdef CONGESTION_DEBUG
848 if (congWindow > INITIAL_WINDOW)
849 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
850 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
851#endif
852
853 // Close congestion window and allow a transfer
854 // FIXME: Reset baseRTT like Linux Vegas?
855 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
856
857 return false;
858 }
859
860 offset = sock->outStream().length();
861
862 // FIXME: Should we compensate for non-update data?
863 // (i.e. use sentOffset instead of offset)
864 if ((offset - ackedOffset) < congWindow)
865 return false;
866
867 // If we just have one outstanding "ping", that means the client has
868 // started receiving our update. In order to not regress compared to
869 // before we had congestion avoidance, we allow another update here.
870 // This could further clog up the tubes, but congestion control isn't
871 // really working properly right now anyway as the wire would otherwise
872 // be idle for at least RTT/2.
873 if (pingCounter == 1)
874 return false;
875
876 return true;
877}
878
879
880void VNCSConnectionST::updateCongestion()
881{
882 unsigned diff;
883
884 if (!seenCongestion)
885 return;
886
887 diff = minRTT - baseRTT;
888
889 if (diff > __rfbmin(100, baseRTT)) {
890 // Way too fast
891 congWindow = congWindow * baseRTT / minRTT;
892 } else if (diff > __rfbmin(50, baseRTT/2)) {
893 // Slightly too fast
894 congWindow -= 4096;
895 } else if (diff < 5) {
896 // Way too slow
897 congWindow += 8192;
898 } else if (diff < 25) {
899 // Too slow
900 congWindow += 4096;
901 }
902
903 if (congWindow < MINIMUM_WINDOW)
904 congWindow = MINIMUM_WINDOW;
905 if (congWindow > MAXIMUM_WINDOW)
906 congWindow = MAXIMUM_WINDOW;
907
908#ifdef CONGESTION_DEBUG
909 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
910 minRTT, baseRTT, congWindow / 1024,
911 congWindow * 8.0 / baseRTT / 1000.0);
912
913#ifdef TCP_INFO
914 struct tcp_info tcp_info;
915 socklen_t tcp_info_length;
916
917 tcp_info_length = sizeof(tcp_info);
918 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
919 (void *)&tcp_info, &tcp_info_length) == 0) {
920 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
921 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
922 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
923 }
924#endif
925
926#endif
927
928 minRTT = -1;
929 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000930}
931
932
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000933void VNCSConnectionST::writeFramebufferUpdate()
934{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000935 Region req;
936 UpdateInfo ui;
937 bool needNewUpdateInfo;
938
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000939 updateTimer.stop();
940
Pierre Ossman2c764942011-11-14 15:54:30 +0000941 // We're in the middle of processing a command that's supposed to be
942 // synchronised. Allowing an update to slip out right now might violate
943 // that synchronisation.
944 if (syncFence)
945 return;
946
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000947 // We try to aggregate responses, so don't send out anything whilst we
948 // still have incoming messages. processMessages() will give us another
949 // chance to run once things are idle.
950 if (inProcessMessages)
951 return;
952
Pierre Ossman1b478e52011-11-15 12:08:30 +0000953 if (state() != RFBSTATE_NORMAL)
954 return;
955 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000956 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000957
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000958 // Check that we actually have some space on the link and retry in a
959 // bit if things are congested.
960 if (isCongested()) {
961 updateTimer.start(50);
962 return;
963 }
964
Pierre Ossmane9962f72009-04-23 12:31:42 +0000965 // First take care of any updates that cannot contain framebuffer data
966 // changes.
967 if (writer()->needNoDataUpdate()) {
968 writer()->writeNoDataUpdate();
969 requested.clear();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000970 if (!continuousUpdates)
971 return;
Pierre Ossmane9962f72009-04-23 12:31:42 +0000972 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000973
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000974 updates.enable_copyrect(cp.useCopyRect);
975
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000976 // Fetch updates from server object, and see if we are allowed to send
977 // anything right now (the framebuffer might have changed in ways we
978 // haven't yet been informed of).
979 if (!server->checkUpdate())
980 return;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +0000981
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000982 // Get the lists of updates. Prior to exporting the data to the `ui' object,
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000983 // getUpdateInfo() will normalize the `updates' object such way that its
Pierre Ossman02e43d72009-03-05 11:57:11 +0000984 // `changed' and `copied' regions would not intersect.
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000985
Pierre Ossman1b478e52011-11-15 12:08:30 +0000986 if (continuousUpdates)
987 req = cuRegion.union_(requested);
988 else
989 req = requested;
990
991 updates.getUpdateInfo(&ui, req);
992 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000993
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000994 // If the previous position of the rendered cursor overlaps the source of the
995 // copy, then when the copy happens the corresponding rectangle in the
996 // destination will be wrong, so add it to the changed region.
997
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000998 if (!ui.copied.is_empty() && !renderedCursorRect.is_empty()) {
999 Rect bogusCopiedCursor = (renderedCursorRect.translate(ui.copy_delta)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001000 .intersect(server->pb->getRect()));
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001001 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001002 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001003 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001004 }
1005 }
1006
1007 // If we need to remove the old rendered cursor, just add the rectangle to
1008 // the changed region.
1009
1010 if (removeRenderedCursor) {
1011 updates.add_changed(renderedCursorRect);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001012 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001013 renderedCursorRect.clear();
1014 removeRenderedCursor = false;
1015 }
1016
1017 // Return if there is nothing to send the client.
1018
1019 if (updates.is_empty() && !writer()->needFakeUpdate() && !drawRenderedCursor)
1020 return;
1021
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001022 // The `updates' object could change, make sure we have valid update info.
1023
1024 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001025 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001026
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001027 // If the client needs a server-side rendered cursor, work out the cursor
1028 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1029 // with the update region, we need to draw the rendered cursor regardless of
1030 // whether it has changed.
1031
1032 if (needRenderedCursor()) {
1033 renderedCursorRect
1034 = (server->renderedCursor.getRect(server->renderedCursorTL)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001035 .intersect(req.get_bounding_rect()));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001036
1037 if (renderedCursorRect.is_empty()) {
1038 drawRenderedCursor = false;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001039 } else if (!ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001040 .intersect(renderedCursorRect).is_empty()) {
1041 drawRenderedCursor = true;
1042 }
1043
1044 // We could remove the new cursor rect from updates here. It's not clear
1045 // whether this is worth it. If we do remove it, then we won't draw over
1046 // the same bit of screen twice, but we have the overhead of a more complex
1047 // region.
1048
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001049 //if (drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001050 // updates.subtract(renderedCursorRect);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001051 // updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001052 //}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001053 }
1054
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001055 if (!ui.is_empty() || writer()->needFakeUpdate() || drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001056 // Compute the number of rectangles. Tight encoder makes the things more
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001057 // complicated as compared to the original VNC4.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001058 writer()->setupCurrentEncoder();
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +00001059 int nRects = (ui.copied.numRects() +
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +00001060 (drawRenderedCursor ? 1 : 0));
Constantin Kaplinsky651606d2007-10-17 17:40:23 +00001061
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001062 std::vector<Rect> rects;
1063 std::vector<Rect>::const_iterator i;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001064 ui.changed.get_rects(&rects);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001065 for (i = rects.begin(); i != rects.end(); i++) {
DRCcd2c5d42011-08-11 11:18:34 +00001066 if (i->width() && i->height()) {
1067 int nUpdateRects = writer()->getNumRects(*i);
1068 if (nUpdateRects == 0 && cp.currentEncoding() == encodingTight) {
1069 nRects = 0xFFFF; break;
1070 }
1071 else
1072 nRects += nUpdateRects;
1073 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001074 }
Pierre Ossman1b478e52011-11-15 12:08:30 +00001075
1076 writeRTTPing();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001077
1078 writer()->writeFramebufferUpdateStart(nRects);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001079
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001080 Region updatedRegion;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001081 writer()->writeRects(ui, &image_getter, &updatedRegion);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001082 updates.subtract(updatedRegion);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001083
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001084 if (drawRenderedCursor)
1085 writeRenderedCursorRect();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001086
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001087 writer()->writeFramebufferUpdateEnd();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001088
1089 writeRTTPing();
1090
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001091 requested.clear();
1092 }
1093}
1094
1095
1096// writeRenderedCursorRect() writes a single rectangle drawing the rendered
1097// cursor on the client.
1098
1099void VNCSConnectionST::writeRenderedCursorRect()
1100{
1101 image_getter.setPixelBuffer(&server->renderedCursor);
1102 image_getter.setOffset(server->renderedCursorTL);
1103
1104 Rect actual;
1105 writer()->writeRect(renderedCursorRect, &image_getter, &actual);
1106
1107 image_getter.setPixelBuffer(server->pb);
1108 image_getter.setOffset(Point(0,0));
1109
1110 drawRenderedCursor = false;
1111}
1112
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001113void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1114{
1115 if (!authenticated())
1116 return;
1117
1118 cp.screenLayout = server->screenLayout;
1119
1120 if (state() != RFBSTATE_NORMAL)
1121 return;
1122
1123 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1124 cp.screenLayout);
1125 writeFramebufferUpdate();
1126}
1127
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001128void VNCSConnectionST::setColourMapEntries(int firstColour, int nColours)
1129{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001130 if (!readyForSetColourMapEntries)
1131 return;
1132 if (server->pb->getPF().trueColour)
1133 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001134
Pierre Ossmana2739342011-03-08 16:53:07 +00001135 image_getter.setColourMapEntries(firstColour, nColours);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001136
1137 if (cp.pf().trueColour) {
1138 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001139 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001140 }
1141}
1142
1143
1144// setCursor() is called whenever the cursor has changed shape or pixel format.
1145// If the client supports local cursor then it will arrange for the cursor to
1146// be sent to the client.
1147
1148void VNCSConnectionST::setCursor()
1149{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001150 if (state() != RFBSTATE_NORMAL)
1151 return;
1152 if (!cp.supportsLocalCursor)
1153 return;
1154
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001155 writer()->cursorChange(this);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001156 writeFramebufferUpdate();
1157}
1158
1159void VNCSConnectionST::setDesktopName(const char *name)
1160{
1161 cp.setName(name);
1162
1163 if (state() != RFBSTATE_NORMAL)
1164 return;
1165
1166 if (!writer()->writeSetDesktopName()) {
1167 fprintf(stderr, "Client does not support desktop rename\n");
1168 return;
1169 }
1170
1171 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001172}
1173
1174void VNCSConnectionST::setSocketTimeouts()
1175{
1176 int timeoutms = rfb::Server::clientWaitTimeMillis;
1177 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1178 if (timeoutms == 0)
1179 timeoutms = -1;
1180 sock->inStream().setTimeout(timeoutms);
1181 sock->outStream().setTimeout(timeoutms);
1182}
1183
1184char* VNCSConnectionST::getStartTime()
1185{
1186 char* result = ctime(&startTime);
1187 result[24] = '\0';
1188 return result;
1189}
1190
1191void VNCSConnectionST::setStatus(int status)
1192{
1193 switch (status) {
1194 case 0:
1195 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1196 break;
1197 case 1:
Adam Tkac8e985062011-02-07 11:33:57 +00001198 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001199 break;
1200 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001201 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001202 break;
1203 }
1204 framebufferUpdateRequest(server->pb->getRect(), false);
1205}
1206int VNCSConnectionST::getStatus()
1207{
1208 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1209 return 0;
1210 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1211 return 1;
1212 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1213 return 2;
1214 return 4;
1215}
1216