blob: 466d6d5c835d72033dcbb65ed92128946dee3580 [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
Pierre Ossmanb114cec2011-11-20 15:36:11 +0000329
330bool VNCSConnectionST::getComparerState()
331{
332 // We interpret a low compression level as an indication that the client
333 // wants to prioritise CPU usage over bandwidth, and hence disable the
334 // comparing update tracker.
335 return (cp.compressLevel == -1) || (cp.compressLevel > 1);
336}
337
338
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000339// renderedCursorChange() is called whenever the server-side rendered cursor
340// changes shape or position. It ensures that the next update will clean up
341// the old rendered cursor and if necessary draw the new rendered cursor.
342
343void VNCSConnectionST::renderedCursorChange()
344{
345 if (state() != RFBSTATE_NORMAL) return;
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000346 if (!renderedCursorRect.is_empty())
347 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000348 if (needRenderedCursor())
349 drawRenderedCursor = true;
350}
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
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000619void VNCSConnectionST::setInitialColourMap()
620{
621 setColourMapEntries(0, 0);
622}
623
Pierre Ossman2c764942011-11-14 15:54:30 +0000624void VNCSConnectionST::fence(rdr::U32 flags, unsigned len, const char data[])
625{
626 if (flags & fenceFlagRequest) {
627 if (flags & fenceFlagSyncNext) {
628 if (syncFence)
629 vlog.error("Fence trying to synchronise another fence");
630
631 syncFence = true;
632
633 fenceFlags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter | fenceFlagSyncNext);
634 fenceDataLen = len;
635 delete [] fenceData;
636 if (len > 0) {
637 fenceData = new char[len];
638 memcpy(fenceData, data, len);
639 }
640
641 return;
642 }
643
644 // We handle everything synchronously so we trivially honor these modes
645 flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter);
646
647 writer()->writeFence(flags, len, data);
648 return;
649 }
650
Pierre Ossman1b478e52011-11-15 12:08:30 +0000651 struct RTTInfo rttInfo;
652
Pierre Ossman2c764942011-11-14 15:54:30 +0000653 switch (len) {
654 case 0:
655 // Initial dummy fence;
656 break;
Pierre Ossman1b478e52011-11-15 12:08:30 +0000657 case sizeof(struct RTTInfo):
658 memcpy(&rttInfo, data, sizeof(struct RTTInfo));
659 handleRTTPong(rttInfo);
660 break;
Pierre Ossman2c764942011-11-14 15:54:30 +0000661 default:
662 vlog.error("Fence response of unexpected size received");
663 }
664}
665
Pierre Ossman1b478e52011-11-15 12:08:30 +0000666void VNCSConnectionST::enableContinuousUpdates(bool enable,
667 int x, int y, int w, int h)
668{
669 Rect rect;
670
671 if (!cp.supportsFence || !cp.supportsContinuousUpdates)
672 throw Exception("Client tried to enable continuous updates when not allowed");
673
674 continuousUpdates = enable;
675
676 rect.setXYWH(x, y, w, h);
677 cuRegion.reset(rect);
678
679 if (enable) {
680 requested.clear();
681 writeFramebufferUpdate();
682 } else {
683 writer()->writeEndOfContinuousUpdates();
684 }
685}
686
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000687// supportsLocalCursor() is called whenever the status of
688// cp.supportsLocalCursor has changed. If the client does now support local
689// cursor, we make sure that the old server-side rendered cursor is cleaned up
690// and the cursor is sent to the client.
691
692void VNCSConnectionST::supportsLocalCursor()
693{
694 if (cp.supportsLocalCursor || cp.supportsLocalXCursor) {
Pierre Ossman5c9e1e52011-11-08 10:32:05 +0000695 if (!renderedCursorRect.is_empty())
696 removeRenderedCursor = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000697 drawRenderedCursor = false;
698 setCursor();
699 }
700}
701
Pierre Ossman2c764942011-11-14 15:54:30 +0000702void VNCSConnectionST::supportsFence()
703{
704 writer()->writeFence(fenceFlagRequest, 0, NULL);
705}
706
Pierre Ossman1b478e52011-11-15 12:08:30 +0000707void VNCSConnectionST::supportsContinuousUpdates()
708{
709 // We refuse to use continuous updates if we cannot monitor the buffer
710 // usage using fences.
711 if (!cp.supportsFence)
712 return;
713
714 writer()->writeEndOfContinuousUpdates();
715}
716
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000717void VNCSConnectionST::writeSetCursorCallback()
718{
719 if (cp.supportsLocalXCursor) {
720 Pixel pix0, pix1;
721 rdr::U8Array bitmap(server->cursor.getBitmap(&pix0, &pix1));
722 if (bitmap.buf) {
723 // The client supports XCursor and the cursor only has two
724 // colors. Use the XCursor encoding.
725 writer()->writeSetXCursor(server->cursor.width(),
726 server->cursor.height(),
727 server->cursor.hotspot.x,
728 server->cursor.hotspot.y,
729 bitmap.buf, server->cursor.mask.buf);
730 return;
731 } else {
732 // More than two colors
733 if (!cp.supportsLocalCursor) {
734 // FIXME: We could reduce to two colors.
735 vlog.info("Unable to send multicolor cursor: RichCursor not supported by client");
736 return;
737 }
738 }
739 }
740
741 // Use RichCursor
742 rdr::U8* transData = writer()->getImageBuf(server->cursor.area());
743 image_getter.translatePixels(server->cursor.data, transData,
744 server->cursor.area());
745 writer()->writeSetCursor(server->cursor.width(),
746 server->cursor.height(),
747 server->cursor.hotspot,
748 transData, server->cursor.mask.buf);
749}
750
751
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000752bool VNCSConnectionST::handleTimeout(Timer* t)
753{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000754 try {
755 if (t == &updateTimer)
756 writeFramebufferUpdate();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000757 else if (t == &congestionTimer)
758 updateCongestion();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000759 } catch (rdr::Exception& e) {
760 close(e.str());
761 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000762
763 return false;
764}
765
766
Pierre Ossman1b478e52011-11-15 12:08:30 +0000767void VNCSConnectionST::writeRTTPing()
768{
769 struct RTTInfo rttInfo;
770
771 if (!cp.supportsFence)
772 return;
773
774 memset(&rttInfo, 0, sizeof(struct RTTInfo));
775
776 gettimeofday(&rttInfo.tv, NULL);
777 rttInfo.offset = sock->outStream().length();
778 rttInfo.inFlight = rttInfo.offset - ackedOffset;
779
780 // We need to make sure any old update are already processed by the
781 // time we get the response back. This allows us to reliably throttle
782 // back on client overload, as well as network overload.
783 writer()->writeFence(fenceFlagRequest | fenceFlagBlockBefore,
784 sizeof(struct RTTInfo), (const char*)&rttInfo);
785
786 pingCounter++;
787
788 sentOffset = rttInfo.offset;
789
790 // Let some data flow before we adjust the settings
791 if (!congestionTimer.isStarted())
792 congestionTimer.start(__rfbmin(baseRTT * 2, 100));
793}
794
795void VNCSConnectionST::handleRTTPong(const struct RTTInfo &rttInfo)
796{
797 unsigned rtt, delay;
798 int bdp;
799
800 pingCounter--;
801
802 rtt = msSince(&rttInfo.tv);
803 if (rtt < 1)
804 rtt = 1;
805
806 ackedOffset = rttInfo.offset;
807
808 // Try to estimate wire latency by tracking lowest seen latency
809 if (rtt < baseRTT)
810 baseRTT = rtt;
811
812 if (rttInfo.inFlight > congWindow) {
813 seenCongestion = true;
814
815 // Estimate added delay because of overtaxed buffers
816 delay = (rttInfo.inFlight - congWindow) * baseRTT / congWindow;
817
818 if (delay < rtt)
819 rtt -= delay;
820 else
821 rtt = 1;
822
823 // If we underestimate the congestion window, then we'll get a latency
824 // that's less than the wire latency, which will confuse other portions
825 // of the code.
826 if (rtt < baseRTT)
827 rtt = baseRTT;
828 }
829
830 // We only keep track of the minimum latency seen (for a given interval)
831 // on the basis that we want to avoid continous buffer issue, but don't
832 // mind (or even approve of) bursts.
833 if (rtt < minRTT)
834 minRTT = rtt;
835}
836
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000837bool VNCSConnectionST::isCongested()
838{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000839 int offset;
840
841 // Stuff still waiting in the send buffer?
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000842 if (sock->outStream().bufferUsage() > 0)
843 return true;
844
Pierre Ossman1b478e52011-11-15 12:08:30 +0000845 if (!cp.supportsFence)
846 return false;
847
848 // Idle for too long? (and no data on the wire)
849 //
850 // FIXME: This should really just be one baseRTT, but we're getting
851 // problems with triggering the idle timeout on each update.
852 // Maybe we need to use a moving average for the wire latency
853 // instead of baseRTT.
854 if ((sentOffset == ackedOffset) &&
855 (sock->outStream().getIdleTime() > 2 * baseRTT)) {
856
857#ifdef CONGESTION_DEBUG
858 if (congWindow > INITIAL_WINDOW)
859 fprintf(stderr, "Reverting to initial window (%d KiB) after %d ms\n",
860 INITIAL_WINDOW / 1024, sock->outStream().getIdleTime());
861#endif
862
863 // Close congestion window and allow a transfer
864 // FIXME: Reset baseRTT like Linux Vegas?
865 congWindow = __rfbmin(INITIAL_WINDOW, congWindow);
866
867 return false;
868 }
869
870 offset = sock->outStream().length();
871
872 // FIXME: Should we compensate for non-update data?
873 // (i.e. use sentOffset instead of offset)
874 if ((offset - ackedOffset) < congWindow)
875 return false;
876
877 // If we just have one outstanding "ping", that means the client has
878 // started receiving our update. In order to not regress compared to
879 // before we had congestion avoidance, we allow another update here.
880 // This could further clog up the tubes, but congestion control isn't
881 // really working properly right now anyway as the wire would otherwise
882 // be idle for at least RTT/2.
883 if (pingCounter == 1)
884 return false;
885
886 return true;
887}
888
889
890void VNCSConnectionST::updateCongestion()
891{
892 unsigned diff;
893
894 if (!seenCongestion)
895 return;
896
897 diff = minRTT - baseRTT;
898
899 if (diff > __rfbmin(100, baseRTT)) {
900 // Way too fast
901 congWindow = congWindow * baseRTT / minRTT;
902 } else if (diff > __rfbmin(50, baseRTT/2)) {
903 // Slightly too fast
904 congWindow -= 4096;
905 } else if (diff < 5) {
906 // Way too slow
907 congWindow += 8192;
908 } else if (diff < 25) {
909 // Too slow
910 congWindow += 4096;
911 }
912
913 if (congWindow < MINIMUM_WINDOW)
914 congWindow = MINIMUM_WINDOW;
915 if (congWindow > MAXIMUM_WINDOW)
916 congWindow = MAXIMUM_WINDOW;
917
918#ifdef CONGESTION_DEBUG
919 fprintf(stderr, "RTT: %d ms (%d ms), Window: %d KiB, Bandwidth: %g Mbps\n",
920 minRTT, baseRTT, congWindow / 1024,
921 congWindow * 8.0 / baseRTT / 1000.0);
922
923#ifdef TCP_INFO
924 struct tcp_info tcp_info;
925 socklen_t tcp_info_length;
926
927 tcp_info_length = sizeof(tcp_info);
928 if (getsockopt(sock->getFd(), SOL_TCP, TCP_INFO,
929 (void *)&tcp_info, &tcp_info_length) == 0) {
930 fprintf(stderr, "Socket: RTT: %d ms (+/- %d ms) Window %d KiB\n",
931 tcp_info.tcpi_rtt / 1000, tcp_info.tcpi_rttvar / 1000,
932 tcp_info.tcpi_snd_mss * tcp_info.tcpi_snd_cwnd / 1024);
933 }
934#endif
935
936#endif
937
938 minRTT = -1;
939 seenCongestion = false;
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000940}
941
942
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000943void VNCSConnectionST::writeFramebufferUpdate()
944{
Pierre Ossman1b478e52011-11-15 12:08:30 +0000945 Region req;
946 UpdateInfo ui;
947 bool needNewUpdateInfo;
948
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000949 updateTimer.stop();
950
Pierre Ossman2c764942011-11-14 15:54:30 +0000951 // We're in the middle of processing a command that's supposed to be
952 // synchronised. Allowing an update to slip out right now might violate
953 // that synchronisation.
954 if (syncFence)
955 return;
956
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000957 // We try to aggregate responses, so don't send out anything whilst we
958 // still have incoming messages. processMessages() will give us another
959 // chance to run once things are idle.
960 if (inProcessMessages)
961 return;
962
Pierre Ossman1b478e52011-11-15 12:08:30 +0000963 if (state() != RFBSTATE_NORMAL)
964 return;
965 if (requested.is_empty() && !continuousUpdates)
Pierre Ossmane9962f72009-04-23 12:31:42 +0000966 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000967
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000968 // Check that we actually have some space on the link and retry in a
969 // bit if things are congested.
970 if (isCongested()) {
971 updateTimer.start(50);
972 return;
973 }
974
Pierre Ossman36dadf82011-11-15 12:11:32 +0000975 // In continuous mode, we will be outputting at least three distinct
976 // messages. We need to aggregate these in order to not clog up TCP's
977 // congestion window.
978 network::TcpSocket::cork(sock->getFd(), true);
979
Pierre Ossmane9962f72009-04-23 12:31:42 +0000980 // First take care of any updates that cannot contain framebuffer data
981 // changes.
982 if (writer()->needNoDataUpdate()) {
983 writer()->writeNoDataUpdate();
984 requested.clear();
Pierre Ossman1b478e52011-11-15 12:08:30 +0000985 if (!continuousUpdates)
Pierre Ossman36dadf82011-11-15 12:11:32 +0000986 goto out;
Pierre Ossmane9962f72009-04-23 12:31:42 +0000987 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000988
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000989 updates.enable_copyrect(cp.useCopyRect);
990
Pierre Ossmanbbf955e2011-11-08 12:44:10 +0000991 // Fetch updates from server object, and see if we are allowed to send
992 // anything right now (the framebuffer might have changed in ways we
993 // haven't yet been informed of).
994 if (!server->checkUpdate())
Pierre Ossman36dadf82011-11-15 12:11:32 +0000995 goto out;
Constantin Kaplinskya09dc142008-12-18 12:08:15 +0000996
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000997 // Get the lists of updates. Prior to exporting the data to the `ui' object,
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000998 // getUpdateInfo() will normalize the `updates' object such way that its
Pierre Ossman02e43d72009-03-05 11:57:11 +0000999 // `changed' and `copied' regions would not intersect.
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001000
Pierre Ossman1b478e52011-11-15 12:08:30 +00001001 if (continuousUpdates)
1002 req = cuRegion.union_(requested);
1003 else
1004 req = requested;
1005
1006 updates.getUpdateInfo(&ui, req);
1007 needNewUpdateInfo = false;
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001008
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001009 // If the previous position of the rendered cursor overlaps the source of the
1010 // copy, then when the copy happens the corresponding rectangle in the
1011 // destination will be wrong, so add it to the changed region.
1012
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001013 if (!ui.copied.is_empty() && !renderedCursorRect.is_empty()) {
1014 Rect bogusCopiedCursor = (renderedCursorRect.translate(ui.copy_delta)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001015 .intersect(server->pb->getRect()));
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001016 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001017 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001018 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001019 }
1020 }
1021
1022 // If we need to remove the old rendered cursor, just add the rectangle to
1023 // the changed region.
1024
1025 if (removeRenderedCursor) {
1026 updates.add_changed(renderedCursorRect);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001027 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001028 renderedCursorRect.clear();
1029 removeRenderedCursor = false;
1030 }
1031
1032 // Return if there is nothing to send the client.
1033
1034 if (updates.is_empty() && !writer()->needFakeUpdate() && !drawRenderedCursor)
Pierre Ossman36dadf82011-11-15 12:11:32 +00001035 goto out;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001036
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001037 // The `updates' object could change, make sure we have valid update info.
1038
1039 if (needNewUpdateInfo)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001040 updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001041
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001042 // If the client needs a server-side rendered cursor, work out the cursor
1043 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
1044 // with the update region, we need to draw the rendered cursor regardless of
1045 // whether it has changed.
1046
1047 if (needRenderedCursor()) {
1048 renderedCursorRect
1049 = (server->renderedCursor.getRect(server->renderedCursorTL)
Pierre Ossman1b478e52011-11-15 12:08:30 +00001050 .intersect(req.get_bounding_rect()));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001051
1052 if (renderedCursorRect.is_empty()) {
1053 drawRenderedCursor = false;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001054 } else if (!ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001055 .intersect(renderedCursorRect).is_empty()) {
1056 drawRenderedCursor = true;
1057 }
1058
1059 // We could remove the new cursor rect from updates here. It's not clear
1060 // whether this is worth it. If we do remove it, then we won't draw over
1061 // the same bit of screen twice, but we have the overhead of a more complex
1062 // region.
1063
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001064 //if (drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001065 // updates.subtract(renderedCursorRect);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001066 // updates.getUpdateInfo(&ui, req);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001067 //}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001068 }
1069
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001070 if (!ui.is_empty() || writer()->needFakeUpdate() || drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001071 // Compute the number of rectangles. Tight encoder makes the things more
Constantin Kaplinsky604d7812007-08-31 15:50:37 +00001072 // complicated as compared to the original VNC4.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001073 writer()->setupCurrentEncoder();
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +00001074 int nRects = (ui.copied.numRects() +
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +00001075 (drawRenderedCursor ? 1 : 0));
Constantin Kaplinsky651606d2007-10-17 17:40:23 +00001076
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001077 std::vector<Rect> rects;
1078 std::vector<Rect>::const_iterator i;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001079 ui.changed.get_rects(&rects);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001080 for (i = rects.begin(); i != rects.end(); i++) {
DRCcd2c5d42011-08-11 11:18:34 +00001081 if (i->width() && i->height()) {
1082 int nUpdateRects = writer()->getNumRects(*i);
1083 if (nUpdateRects == 0 && cp.currentEncoding() == encodingTight) {
1084 nRects = 0xFFFF; break;
1085 }
1086 else
1087 nRects += nUpdateRects;
1088 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001089 }
Pierre Ossman1b478e52011-11-15 12:08:30 +00001090
1091 writeRTTPing();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001092
1093 writer()->writeFramebufferUpdateStart(nRects);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001094
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001095 Region updatedRegion;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +00001096 writer()->writeRects(ui, &image_getter, &updatedRegion);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001097 updates.subtract(updatedRegion);
Pierre Ossman1b478e52011-11-15 12:08:30 +00001098
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001099 if (drawRenderedCursor)
1100 writeRenderedCursorRect();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001101
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001102 writer()->writeFramebufferUpdateEnd();
Pierre Ossman1b478e52011-11-15 12:08:30 +00001103
1104 writeRTTPing();
1105
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001106 requested.clear();
1107 }
Pierre Ossman36dadf82011-11-15 12:11:32 +00001108
1109out:
1110 network::TcpSocket::cork(sock->getFd(), false);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001111}
1112
1113
1114// writeRenderedCursorRect() writes a single rectangle drawing the rendered
1115// cursor on the client.
1116
1117void VNCSConnectionST::writeRenderedCursorRect()
1118{
1119 image_getter.setPixelBuffer(&server->renderedCursor);
1120 image_getter.setOffset(server->renderedCursorTL);
1121
1122 Rect actual;
1123 writer()->writeRect(renderedCursorRect, &image_getter, &actual);
1124
1125 image_getter.setPixelBuffer(server->pb);
1126 image_getter.setOffset(Point(0,0));
1127
1128 drawRenderedCursor = false;
1129}
1130
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001131void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
1132{
1133 if (!authenticated())
1134 return;
1135
1136 cp.screenLayout = server->screenLayout;
1137
1138 if (state() != RFBSTATE_NORMAL)
1139 return;
1140
1141 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
1142 cp.screenLayout);
1143 writeFramebufferUpdate();
1144}
1145
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001146void VNCSConnectionST::setColourMapEntries(int firstColour, int nColours)
1147{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001148 if (!readyForSetColourMapEntries)
1149 return;
1150 if (server->pb->getPF().trueColour)
1151 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001152
Pierre Ossmana2739342011-03-08 16:53:07 +00001153 image_getter.setColourMapEntries(firstColour, nColours);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001154
1155 if (cp.pf().trueColour) {
1156 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001157 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001158 }
1159}
1160
1161
1162// setCursor() is called whenever the cursor has changed shape or pixel format.
1163// If the client supports local cursor then it will arrange for the cursor to
1164// be sent to the client.
1165
1166void VNCSConnectionST::setCursor()
1167{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001168 if (state() != RFBSTATE_NORMAL)
1169 return;
1170 if (!cp.supportsLocalCursor)
1171 return;
1172
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001173 writer()->cursorChange(this);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +00001174 writeFramebufferUpdate();
1175}
1176
1177void VNCSConnectionST::setDesktopName(const char *name)
1178{
1179 cp.setName(name);
1180
1181 if (state() != RFBSTATE_NORMAL)
1182 return;
1183
1184 if (!writer()->writeSetDesktopName()) {
1185 fprintf(stderr, "Client does not support desktop rename\n");
1186 return;
1187 }
1188
1189 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001190}
1191
1192void VNCSConnectionST::setSocketTimeouts()
1193{
1194 int timeoutms = rfb::Server::clientWaitTimeMillis;
1195 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
1196 if (timeoutms == 0)
1197 timeoutms = -1;
1198 sock->inStream().setTimeout(timeoutms);
1199 sock->outStream().setTimeout(timeoutms);
1200}
1201
1202char* VNCSConnectionST::getStartTime()
1203{
1204 char* result = ctime(&startTime);
1205 result[24] = '\0';
1206 return result;
1207}
1208
1209void VNCSConnectionST::setStatus(int status)
1210{
1211 switch (status) {
1212 case 0:
1213 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
1214 break;
1215 case 1:
Adam Tkac8e985062011-02-07 11:33:57 +00001216 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001217 break;
1218 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +00001219 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001220 break;
1221 }
1222 framebufferUpdateRequest(server->pb->getRect(), false);
1223}
1224int VNCSConnectionST::getStatus()
1225{
1226 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
1227 return 0;
1228 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
1229 return 1;
1230 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
1231 return 2;
1232 return 4;
1233}
1234