blob: 84fc2ca1b388f77d2283d146369d58b8bafe7619 [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
20#include <rfb/VNCSConnectionST.h>
21#include <rfb/LogWriter.h>
Adam Tkac5a0caed2010-04-23 13:58:10 +000022#include <rfb/Security.h>
Pierre Ossmanc5e25602009-03-20 12:59:05 +000023#include <rfb/screenTypes.h>
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000024#include <rfb/ServerCore.h>
25#include <rfb/ComparingUpdateTracker.h>
26#include <rfb/KeyRemapper.h>
27#define XK_MISCELLANY
28#define XK_XKB_KEYS
29#include <rfb/keysymdef.h>
30
31using namespace rfb;
32
33static LogWriter vlog("VNCSConnST");
34
35VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s,
36 bool reverse)
Pierre Ossmana3ac01e2011-11-07 21:13:54 +000037 : SConnection(reverse), sock(s), inProcessMessages(false), server(server_),
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000038 updates(false), image_getter(server->useEconomicTranslate),
39 drawRenderedCursor(false), removeRenderedCursor(false),
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +000040 updateTimer(this), pointerEventTime(0),
41 accessRights(AccessDefault), startTime(time(0))
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000042{
43 setStreams(&sock->inStream(), &sock->outStream());
44 peerEndpoint.buf = sock->getPeerEndpoint();
45 VNCServerST::connectionsLog.write(1,"accepted: %s", peerEndpoint.buf);
46
47 // Configure the socket
48 setSocketTimeouts();
49 lastEventTime = time(0);
50
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000051 server->clients.push_front(this);
52}
53
54
55VNCSConnectionST::~VNCSConnectionST()
56{
57 // If we reach here then VNCServerST is deleting us!
58 VNCServerST::connectionsLog.write(1,"closed: %s (%s)",
59 peerEndpoint.buf,
60 (closeReason.buf) ? closeReason.buf : "");
61
62 // Release any keys the client still had pressed
63 std::set<rdr::U32>::iterator i;
64 for (i=pressedKeys.begin(); i!=pressedKeys.end(); i++)
65 server->desktop->keyEvent(*i, false);
66 if (server->pointerClient == this)
67 server->pointerClient = 0;
68
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000069 // Remove this client from the server
70 server->clients.remove(this);
71
72}
73
74
75// Methods called from VNCServerST
76
77bool VNCSConnectionST::init()
78{
79 try {
80 initialiseProtocol();
81 } catch (rdr::Exception& e) {
82 close(e.str());
83 return false;
84 }
85 return true;
86}
87
88void VNCSConnectionST::close(const char* reason)
89{
90 // Log the reason for the close
91 if (!closeReason.buf)
Adam Tkacd36b6262009-09-04 10:57:20 +000092 closeReason.buf = strDup(reason);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +000093 else
94 vlog.debug("second close: %s (%s)", peerEndpoint.buf, reason);
95
96 if (authenticated()) {
97 server->lastDisconnectTime = time(0);
98 }
99
100 // Just shutdown the socket and mark our state as closing. Eventually the
101 // calling code will call VNCServerST's removeSocket() method causing us to
102 // be deleted.
103 sock->shutdown();
104 setState(RFBSTATE_CLOSING);
105}
106
107
108void VNCSConnectionST::processMessages()
109{
110 if (state() == RFBSTATE_CLOSING) return;
111 try {
112 // - Now set appropriate socket timeouts and process data
113 setSocketTimeouts();
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000114
115 inProcessMessages = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000116
117 while (getInStream()->checkNoWait(1)) {
118 processMsg();
119 }
120
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000121 inProcessMessages = false;
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000122
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000123 // If there were anything requiring an update, try to send it here.
124 // We wait until now with this to aggregate responses and to give
125 // higher priority to user actions such as keyboard and pointer events.
126 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000127 } catch (rdr::EndOfStream&) {
128 close("Clean disconnection");
129 } catch (rdr::Exception &e) {
130 close(e.str());
131 }
132}
133
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000134void VNCSConnectionST::pixelBufferChange()
135{
136 try {
137 if (!authenticated()) return;
138 if (cp.width && cp.height && (server->pb->width() != cp.width ||
139 server->pb->height() != cp.height))
140 {
141 // We need to clip the next update to the new size, but also add any
142 // extra bits if it's bigger. If we wanted to do this exactly, something
143 // like the code below would do it, but at the moment we just update the
144 // entire new size. However, we do need to clip the renderedCursorRect
145 // because that might be added to updates in writeFramebufferUpdate().
146
147 //updates.intersect(server->pb->getRect());
148 //
149 //if (server->pb->width() > cp.width)
150 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
151 // server->pb->height()));
152 //if (server->pb->height() > cp.height)
153 // updates.add_changed(Rect(0, cp.height, cp.width,
154 // server->pb->height()));
155
156 renderedCursorRect = renderedCursorRect.intersect(server->pb->getRect());
157
158 cp.width = server->pb->width();
159 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000160 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000161 if (state() == RFBSTATE_NORMAL) {
Pierre Ossman2ee430a2009-05-28 12:54:24 +0000162 // We should only send EDS to client asking for both
163 if (!writer()->writeExtendedDesktopSize()) {
164 if (!writer()->writeSetDesktopSize()) {
165 close("Client does not support desktop resize");
166 return;
167 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000168 }
169 }
170 }
171 // Just update the whole screen at the moment because we're too lazy to
172 // work out what's actually changed.
173 updates.clear();
174 updates.add_changed(server->pb->getRect());
175 vlog.debug("pixel buffer changed - re-initialising image getter");
176 image_getter.init(server->pb, cp.pf(), writer());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000177 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000178 } catch(rdr::Exception &e) {
179 close(e.str());
180 }
181}
182
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000183void VNCSConnectionST::writeFramebufferUpdateOrClose()
Pierre Ossman04e62db2009-03-23 16:57:07 +0000184{
185 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000186 writeFramebufferUpdate();
187 } catch(rdr::Exception &e) {
188 close(e.str());
189 }
190}
Pierre Ossman04e62db2009-03-23 16:57:07 +0000191
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000192void VNCSConnectionST::screenLayoutChangeOrClose(rdr::U16 reason)
193{
194 try {
195 screenLayoutChange(reason);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000196 } catch(rdr::Exception &e) {
197 close(e.str());
198 }
199}
200
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000201void VNCSConnectionST::setColourMapEntriesOrClose(int firstColour,int nColours)
202{
203 try {
204 setColourMapEntries(firstColour, nColours);
205 } catch(rdr::Exception& e) {
206 close(e.str());
207 }
208}
209
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000210void VNCSConnectionST::bellOrClose()
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000211{
212 try {
213 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
214 } catch(rdr::Exception& e) {
215 close(e.str());
216 }
217}
218
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000219void VNCSConnectionST::serverCutTextOrClose(const char *str, int len)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000220{
221 try {
222 if (!(accessRights & AccessCutText)) return;
223 if (!rfb::Server::sendCutText) return;
224 if (state() == RFBSTATE_NORMAL)
225 writer()->writeServerCutText(str, len);
226 } catch(rdr::Exception& e) {
227 close(e.str());
228 }
229}
230
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000231
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000232void VNCSConnectionST::setDesktopNameOrClose(const char *name)
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000233{
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000234 try {
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000235 setDesktopName(name);
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000236 } catch(rdr::Exception& e) {
237 close(e.str());
238 }
239}
240
241
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000242void VNCSConnectionST::setCursorOrClose()
243{
244 try {
245 setCursor();
246 } catch(rdr::Exception& e) {
247 close(e.str());
248 }
249}
250
251
252int VNCSConnectionST::checkIdleTimeout()
253{
254 int idleTimeout = rfb::Server::idleTimeout;
255 if (idleTimeout == 0) return 0;
256 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
257 idleTimeout = 15; // minimum of 15 seconds while authenticating
258 time_t now = time(0);
259 if (now < lastEventTime) {
260 // Someone must have set the time backwards. Set lastEventTime so that the
261 // idleTimeout will count from now.
262 vlog.info("Time has gone backwards - resetting idle timeout");
263 lastEventTime = now;
264 }
265 int timeLeft = lastEventTime + idleTimeout - now;
266 if (timeLeft < -60) {
267 // Our callback is over a minute late - someone must have set the time
268 // forwards. Set lastEventTime so that the idleTimeout will count from
269 // now.
270 vlog.info("Time has gone forwards - resetting idle timeout");
271 lastEventTime = now;
272 return secsToMillis(idleTimeout);
273 }
274 if (timeLeft <= 0) {
275 close("Idle timeout");
276 return 0;
277 }
278 return secsToMillis(timeLeft);
279}
280
281// renderedCursorChange() is called whenever the server-side rendered cursor
282// changes shape or position. It ensures that the next update will clean up
283// the old rendered cursor and if necessary draw the new rendered cursor.
284
285void VNCSConnectionST::renderedCursorChange()
286{
287 if (state() != RFBSTATE_NORMAL) return;
288 removeRenderedCursor = true;
289 if (needRenderedCursor())
290 drawRenderedCursor = true;
291}
292
293// needRenderedCursor() returns true if this client needs the server-side
294// rendered cursor. This may be because it does not support local cursor or
295// because the current cursor position has not been set by this client.
296// Unfortunately we can't know for sure when the current cursor position has
297// been set by this client. We guess that this is the case when the current
298// cursor position is the same as the last pointer event from this client, or
299// if it is a very short time since this client's last pointer event (up to a
300// second). [ Ideally we should do finer-grained timing here and make the time
301// configurable, but I don't think it's that important. ]
302
303bool VNCSConnectionST::needRenderedCursor()
304{
Peter Ã…strandffeeb262010-02-10 09:29:00 +0000305 bool pointerpos = (!server->cursorPos.equals(pointerEventPos) && (time(0) - pointerEventTime) > 0);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000306 return (state() == RFBSTATE_NORMAL
Peter Ã…strandffeeb262010-02-10 09:29:00 +0000307 && ((!cp.supportsLocalCursor && !cp.supportsLocalXCursor) || pointerpos));
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000308}
309
310
311void VNCSConnectionST::approveConnectionOrClose(bool accept,
312 const char* reason)
313{
314 try {
315 approveConnection(accept, reason);
316 } catch (rdr::Exception& e) {
317 close(e.str());
318 }
319}
320
321
322
323// -=- Callbacks from SConnection
324
325void VNCSConnectionST::authSuccess()
326{
327 lastEventTime = time(0);
328
329 server->startDesktop();
330
331 // - Set the connection parameters appropriately
332 cp.width = server->pb->width();
333 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000334 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000335 cp.setName(server->getName());
336
337 // - Set the default pixel format
338 cp.setPF(server->pb->getPF());
339 char buffer[256];
340 cp.pf().print(buffer, 256);
341 vlog.info("Server default pixel format %s", buffer);
342 image_getter.init(server->pb, cp.pf(), 0);
343
344 // - Mark the entire display as "dirty"
345 updates.add_changed(server->pb->getRect());
346 startTime = time(0);
347}
348
349void VNCSConnectionST::queryConnection(const char* userName)
350{
351 // - Authentication succeeded - clear from blacklist
352 CharArray name; name.buf = sock->getPeerAddress();
353 server->blHosts->clearBlackmark(name.buf);
354
355 // - Special case to provide a more useful error message
356 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
357 server->authClientCount() > 0) {
358 approveConnection(false, "The server is already in use");
359 return;
360 }
361
362 // - Does the client have the right to bypass the query?
363 if (reverseConnection ||
364 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
365 (accessRights & AccessNoQuery))
366 {
367 approveConnection(true);
368 return;
369 }
370
371 // - Get the server to display an Accept/Reject dialog, if required
372 // If a dialog is displayed, the result will be PENDING, and the
373 // server will call approveConnection at a later time
374 CharArray reason;
375 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
376 &reason.buf);
377 if (qr == VNCServerST::PENDING)
378 return;
379
380 // - If server returns ACCEPT/REJECT then pass result to SConnection
381 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
382}
383
384void VNCSConnectionST::clientInit(bool shared)
385{
386 lastEventTime = time(0);
387 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
388 if (rfb::Server::neverShared) shared = false;
389 if (!shared) {
390 if (rfb::Server::disconnectClients) {
391 // - Close all the other connected clients
392 vlog.debug("non-shared connection - closing clients");
393 server->closeClients("Non-shared connection requested", getSock());
394 } else {
395 // - Refuse this connection if there are existing clients, in addition to
396 // this one
397 if (server->authClientCount() > 1) {
398 close("Server is already in use");
399 return;
400 }
401 }
402 }
403 SConnection::clientInit(shared);
404}
405
406void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
407{
408 SConnection::setPixelFormat(pf);
409 char buffer[256];
410 pf.print(buffer, 256);
411 vlog.info("Client pixel format %s", buffer);
412 image_getter.init(server->pb, pf, writer());
413 setCursor();
414}
415
416void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
417{
418 pointerEventTime = lastEventTime = time(0);
419 server->lastUserInputTime = lastEventTime;
420 if (!(accessRights & AccessPtrEvents)) return;
421 if (!rfb::Server::acceptPointerEvents) return;
422 if (!server->pointerClient || server->pointerClient == this) {
423 pointerEventPos = pos;
424 if (buttonMask)
425 server->pointerClient = this;
426 else
427 server->pointerClient = 0;
428 server->desktop->pointerEvent(pointerEventPos, buttonMask);
429 }
430}
431
432
433class VNCSConnectionSTShiftPresser {
434public:
435 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
436 : desktop(desktop_), pressed(false) {}
437 ~VNCSConnectionSTShiftPresser() {
438 if (pressed) { desktop->keyEvent(XK_Shift_L, false); }
439 }
440 void press() {
441 desktop->keyEvent(XK_Shift_L, true);
442 pressed = true;
443 }
444 SDesktop* desktop;
445 bool pressed;
446};
447
448// keyEvent() - record in the pressedKeys which keys were pressed. Allow
449// multiple down events (for autorepeat), but only allow a single up event.
450void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
451 lastEventTime = time(0);
452 server->lastUserInputTime = lastEventTime;
453 if (!(accessRights & AccessKeyEvents)) return;
454 if (!rfb::Server::acceptKeyEvents) return;
455
456 // Remap the key if required
457 if (server->keyRemapper)
458 key = server->keyRemapper->remapKey(key);
459
460 // Turn ISO_Left_Tab into shifted Tab.
461 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
462 if (key == XK_ISO_Left_Tab) {
463 if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
464 pressedKeys.find(XK_Shift_R) == pressedKeys.end())
465 shiftPresser.press();
466 key = XK_Tab;
467 }
468
469 if (down) {
470 pressedKeys.insert(key);
471 } else {
472 if (!pressedKeys.erase(key)) return;
473 }
474 server->desktop->keyEvent(key, down);
475}
476
477void VNCSConnectionST::clientCutText(const char* str, int len)
478{
479 if (!(accessRights & AccessCutText)) return;
480 if (!rfb::Server::acceptCutText) return;
481 server->desktop->clientCutText(str, len);
482}
483
484void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
485{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000486 Rect safeRect;
487
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000488 if (!(accessRights & AccessView)) return;
489
490 SConnection::framebufferUpdateRequest(r, incremental);
491
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000492 // Check that the client isn't sending crappy requests
493 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
494 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
495 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000496 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
497 } else {
498 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000499 }
500
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000501 // Just update the requested region.
502 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000503 Region reqRgn(r);
504 requested.assign_union(reqRgn);
505
506 if (!incremental) {
507 // Non-incremental update - treat as if area requested has changed
508 updates.add_changed(reqRgn);
509 server->comparer->add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000510
511 // And send the screen layout to the client (which, unlike the
512 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000513 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000514
515 // We do not send a DesktopSize since it only contains the
516 // framebuffer size (which the client already should know) and
517 // because some clients don't handle extra DesktopSize events
518 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000519 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000520}
521
Pierre Ossman34bb0612009-03-21 21:16:14 +0000522void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
523 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000524{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000525 unsigned int result;
526
527 // Don't bother the desktop with an invalid configuration
528 if (!layout.validate(fb_width, fb_height)) {
529 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
530 fb_width, fb_height, layout);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000531 writeFramebufferUpdate();
Pierre Ossman04e62db2009-03-23 16:57:07 +0000532 return;
533 }
534
535 // FIXME: the desktop will call back to VNCServerST and an extra set
536 // of ExtendedDesktopSize messages will be sent. This is okay
537 // protocol-wise, but unnecessary.
538 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
539
Pierre Ossman04e62db2009-03-23 16:57:07 +0000540 writer()->writeExtendedDesktopSize(reasonClient, result,
541 fb_width, fb_height, layout);
Pierre Ossman04e62db2009-03-23 16:57:07 +0000542
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000543 // Only notify other clients on success
Pierre Ossman04e62db2009-03-23 16:57:07 +0000544 if (result == resultSuccess) {
545 if (server->screenLayout != layout)
546 throw Exception("Desktop configured a different screen layout than requested");
547 server->notifyScreenLayoutChange(this);
548 }
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000549
550 // but always send back a reply to the requesting client
551 // (do this last as it might throw an exception on socket errors)
552 writeFramebufferUpdate();
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000553}
554
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000555void VNCSConnectionST::setInitialColourMap()
556{
557 setColourMapEntries(0, 0);
558}
559
560// supportsLocalCursor() is called whenever the status of
561// cp.supportsLocalCursor has changed. If the client does now support local
562// cursor, we make sure that the old server-side rendered cursor is cleaned up
563// and the cursor is sent to the client.
564
565void VNCSConnectionST::supportsLocalCursor()
566{
567 if (cp.supportsLocalCursor || cp.supportsLocalXCursor) {
568 removeRenderedCursor = true;
569 drawRenderedCursor = false;
570 setCursor();
571 }
572}
573
574void VNCSConnectionST::writeSetCursorCallback()
575{
576 if (cp.supportsLocalXCursor) {
577 Pixel pix0, pix1;
578 rdr::U8Array bitmap(server->cursor.getBitmap(&pix0, &pix1));
579 if (bitmap.buf) {
580 // The client supports XCursor and the cursor only has two
581 // colors. Use the XCursor encoding.
582 writer()->writeSetXCursor(server->cursor.width(),
583 server->cursor.height(),
584 server->cursor.hotspot.x,
585 server->cursor.hotspot.y,
586 bitmap.buf, server->cursor.mask.buf);
587 return;
588 } else {
589 // More than two colors
590 if (!cp.supportsLocalCursor) {
591 // FIXME: We could reduce to two colors.
592 vlog.info("Unable to send multicolor cursor: RichCursor not supported by client");
593 return;
594 }
595 }
596 }
597
598 // Use RichCursor
599 rdr::U8* transData = writer()->getImageBuf(server->cursor.area());
600 image_getter.translatePixels(server->cursor.data, transData,
601 server->cursor.area());
602 writer()->writeSetCursor(server->cursor.width(),
603 server->cursor.height(),
604 server->cursor.hotspot,
605 transData, server->cursor.mask.buf);
606}
607
608
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000609bool VNCSConnectionST::handleTimeout(Timer* t)
610{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000611 try {
612 if (t == &updateTimer)
613 writeFramebufferUpdate();
614 } catch (rdr::Exception& e) {
615 close(e.str());
616 }
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000617
618 return false;
619}
620
621
622bool VNCSConnectionST::isCongested()
623{
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000624 if (sock->outStream().bufferUsage() > 0)
625 return true;
626
627 return false;
628}
629
630
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000631void VNCSConnectionST::writeFramebufferUpdate()
632{
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000633 updateTimer.stop();
634
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000635 // We try to aggregate responses, so don't send out anything whilst we
636 // still have incoming messages. processMessages() will give us another
637 // chance to run once things are idle.
638 if (inProcessMessages)
639 return;
640
Pierre Ossmane9962f72009-04-23 12:31:42 +0000641 if (state() != RFBSTATE_NORMAL || requested.is_empty())
642 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000643
Pierre Ossman1bb8b6c2011-10-25 15:20:05 +0000644 // Check that we actually have some space on the link and retry in a
645 // bit if things are congested.
646 if (isCongested()) {
647 updateTimer.start(50);
648 return;
649 }
650
Pierre Ossmane9962f72009-04-23 12:31:42 +0000651 // First take care of any updates that cannot contain framebuffer data
652 // changes.
653 if (writer()->needNoDataUpdate()) {
654 writer()->writeNoDataUpdate();
655 requested.clear();
656 return;
657 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000658
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000659 updates.enable_copyrect(cp.useCopyRect);
660
Pierre Ossman02e43d72009-03-05 11:57:11 +0000661 server->checkUpdate();
Constantin Kaplinskya09dc142008-12-18 12:08:15 +0000662
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000663 // Get the lists of updates. Prior to exporting the data to the `ui' object,
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000664 // getUpdateInfo() will normalize the `updates' object such way that its
Pierre Ossman02e43d72009-03-05 11:57:11 +0000665 // `changed' and `copied' regions would not intersect.
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000666
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000667 UpdateInfo ui;
668 updates.getUpdateInfo(&ui, requested);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000669 bool needNewUpdateInfo = false;
670
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000671 // If the previous position of the rendered cursor overlaps the source of the
672 // copy, then when the copy happens the corresponding rectangle in the
673 // destination will be wrong, so add it to the changed region.
674
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000675 if (!ui.copied.is_empty() && !renderedCursorRect.is_empty()) {
676 Rect bogusCopiedCursor = (renderedCursorRect.translate(ui.copy_delta)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000677 .intersect(server->pb->getRect()));
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000678 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000679 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000680 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000681 }
682 }
683
684 // If we need to remove the old rendered cursor, just add the rectangle to
685 // the changed region.
686
687 if (removeRenderedCursor) {
688 updates.add_changed(renderedCursorRect);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000689 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000690 renderedCursorRect.clear();
691 removeRenderedCursor = false;
692 }
693
694 // Return if there is nothing to send the client.
695
696 if (updates.is_empty() && !writer()->needFakeUpdate() && !drawRenderedCursor)
697 return;
698
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000699 // The `updates' object could change, make sure we have valid update info.
700
701 if (needNewUpdateInfo)
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000702 updates.getUpdateInfo(&ui, requested);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000703
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000704 // If the client needs a server-side rendered cursor, work out the cursor
705 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
706 // with the update region, we need to draw the rendered cursor regardless of
707 // whether it has changed.
708
709 if (needRenderedCursor()) {
710 renderedCursorRect
711 = (server->renderedCursor.getRect(server->renderedCursorTL)
712 .intersect(requested.get_bounding_rect()));
713
714 if (renderedCursorRect.is_empty()) {
715 drawRenderedCursor = false;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000716 } else if (!ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000717 .intersect(renderedCursorRect).is_empty()) {
718 drawRenderedCursor = true;
719 }
720
721 // We could remove the new cursor rect from updates here. It's not clear
722 // whether this is worth it. If we do remove it, then we won't draw over
723 // the same bit of screen twice, but we have the overhead of a more complex
724 // region.
725
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000726 //if (drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000727 // updates.subtract(renderedCursorRect);
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000728 // updates.getUpdateInfo(&ui, requested);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000729 //}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000730 }
731
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000732 if (!ui.is_empty() || writer()->needFakeUpdate() || drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000733 // Compute the number of rectangles. Tight encoder makes the things more
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000734 // complicated as compared to the original VNC4.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000735 writer()->setupCurrentEncoder();
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000736 int nRects = (ui.copied.numRects() +
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000737 (drawRenderedCursor ? 1 : 0));
Constantin Kaplinsky651606d2007-10-17 17:40:23 +0000738
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000739 std::vector<Rect> rects;
740 std::vector<Rect>::const_iterator i;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000741 ui.changed.get_rects(&rects);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000742 for (i = rects.begin(); i != rects.end(); i++) {
DRCcd2c5d42011-08-11 11:18:34 +0000743 if (i->width() && i->height()) {
744 int nUpdateRects = writer()->getNumRects(*i);
745 if (nUpdateRects == 0 && cp.currentEncoding() == encodingTight) {
746 nRects = 0xFFFF; break;
747 }
748 else
749 nRects += nUpdateRects;
750 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000751 }
752
753 writer()->writeFramebufferUpdateStart(nRects);
754 Region updatedRegion;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000755 writer()->writeRects(ui, &image_getter, &updatedRegion);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000756 updates.subtract(updatedRegion);
757 if (drawRenderedCursor)
758 writeRenderedCursorRect();
759 writer()->writeFramebufferUpdateEnd();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000760 requested.clear();
761 }
762}
763
764
765// writeRenderedCursorRect() writes a single rectangle drawing the rendered
766// cursor on the client.
767
768void VNCSConnectionST::writeRenderedCursorRect()
769{
770 image_getter.setPixelBuffer(&server->renderedCursor);
771 image_getter.setOffset(server->renderedCursorTL);
772
773 Rect actual;
774 writer()->writeRect(renderedCursorRect, &image_getter, &actual);
775
776 image_getter.setPixelBuffer(server->pb);
777 image_getter.setOffset(Point(0,0));
778
779 drawRenderedCursor = false;
780}
781
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000782void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
783{
784 if (!authenticated())
785 return;
786
787 cp.screenLayout = server->screenLayout;
788
789 if (state() != RFBSTATE_NORMAL)
790 return;
791
792 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
793 cp.screenLayout);
794 writeFramebufferUpdate();
795}
796
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000797void VNCSConnectionST::setColourMapEntries(int firstColour, int nColours)
798{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000799 if (!readyForSetColourMapEntries)
800 return;
801 if (server->pb->getPF().trueColour)
802 return;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000803
Pierre Ossmana2739342011-03-08 16:53:07 +0000804 image_getter.setColourMapEntries(firstColour, nColours);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000805
806 if (cp.pf().trueColour) {
807 updates.add_changed(server->pb->getRect());
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000808 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000809 }
810}
811
812
813// setCursor() is called whenever the cursor has changed shape or pixel format.
814// If the client supports local cursor then it will arrange for the cursor to
815// be sent to the client.
816
817void VNCSConnectionST::setCursor()
818{
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000819 if (state() != RFBSTATE_NORMAL)
820 return;
821 if (!cp.supportsLocalCursor)
822 return;
823
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000824 writer()->cursorChange(this);
Pierre Ossmana3ac01e2011-11-07 21:13:54 +0000825 writeFramebufferUpdate();
826}
827
828void VNCSConnectionST::setDesktopName(const char *name)
829{
830 cp.setName(name);
831
832 if (state() != RFBSTATE_NORMAL)
833 return;
834
835 if (!writer()->writeSetDesktopName()) {
836 fprintf(stderr, "Client does not support desktop rename\n");
837 return;
838 }
839
840 writeFramebufferUpdate();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000841}
842
843void VNCSConnectionST::setSocketTimeouts()
844{
845 int timeoutms = rfb::Server::clientWaitTimeMillis;
846 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
847 if (timeoutms == 0)
848 timeoutms = -1;
849 sock->inStream().setTimeout(timeoutms);
850 sock->outStream().setTimeout(timeoutms);
851}
852
853char* VNCSConnectionST::getStartTime()
854{
855 char* result = ctime(&startTime);
856 result[24] = '\0';
857 return result;
858}
859
860void VNCSConnectionST::setStatus(int status)
861{
862 switch (status) {
863 case 0:
864 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
865 break;
866 case 1:
Adam Tkac8e985062011-02-07 11:33:57 +0000867 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents) | AccessView;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000868 break;
869 case 2:
Adam Tkac8e985062011-02-07 11:33:57 +0000870 accessRights = accessRights & ~(AccessPtrEvents | AccessKeyEvents | AccessView);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000871 break;
872 }
873 framebufferUpdateRequest(server->pb->getRect(), false);
874}
875int VNCSConnectionST::getStatus()
876{
877 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
878 return 0;
879 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
880 return 1;
881 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
882 return 2;
883 return 4;
884}
885