blob: 9b4d38ef390e83e13823134138414eacec222a30 [file] [log] [blame]
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
Pierre Ossmanc5e25602009-03-20 12:59:05 +00002 * Copyright 2009 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>
22#include <rfb/secTypes.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)
37 : SConnection(server_->securityFactory, reverse), sock(s), server(server_),
38 updates(false), image_getter(server->useEconomicTranslate),
39 drawRenderedCursor(false), removeRenderedCursor(false),
40 pointerEventTime(0), accessRights(AccessDefault),
Pierre Ossmanf99c5712009-03-13 14:41:27 +000041 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)
92 closeReason.buf = strDup(reason);
93 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();
114 bool clientsReadyBefore = server->clientsReadyForUpdate();
115
116 while (getInStream()->checkNoWait(1)) {
117 processMsg();
118 }
119
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000120 // If there were update requests, try to send a framebuffer update.
Pierre Ossman02e43d72009-03-05 11:57:11 +0000121 // We don't send updates immediately on requests as this way, we
122 // give higher priority to user actions such as keyboard and
123 // pointer events.
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000124 if (!requested.is_empty()) {
125 writeFramebufferUpdate();
126 }
127
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000128 if (!clientsReadyBefore && !requested.is_empty())
129 server->desktop->framebufferUpdateRequest();
130 } catch (rdr::EndOfStream&) {
131 close("Clean disconnection");
132 } catch (rdr::Exception &e) {
133 close(e.str());
134 }
135}
136
137void VNCSConnectionST::writeFramebufferUpdateOrClose()
138{
139 try {
140 writeFramebufferUpdate();
141 } catch(rdr::Exception &e) {
142 close(e.str());
143 }
144}
145
146void VNCSConnectionST::pixelBufferChange()
147{
148 try {
149 if (!authenticated()) return;
150 if (cp.width && cp.height && (server->pb->width() != cp.width ||
151 server->pb->height() != cp.height))
152 {
153 // We need to clip the next update to the new size, but also add any
154 // extra bits if it's bigger. If we wanted to do this exactly, something
155 // like the code below would do it, but at the moment we just update the
156 // entire new size. However, we do need to clip the renderedCursorRect
157 // because that might be added to updates in writeFramebufferUpdate().
158
159 //updates.intersect(server->pb->getRect());
160 //
161 //if (server->pb->width() > cp.width)
162 // updates.add_changed(Rect(cp.width, 0, server->pb->width(),
163 // server->pb->height()));
164 //if (server->pb->height() > cp.height)
165 // updates.add_changed(Rect(0, cp.height, cp.width,
166 // server->pb->height()));
167
168 renderedCursorRect = renderedCursorRect.intersect(server->pb->getRect());
169
170 cp.width = server->pb->width();
171 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000172 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000173 if (state() == RFBSTATE_NORMAL) {
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000174 if (!writer()->writeSetDesktopSize() &&
175 !writer()->writeExtendedDesktopSize()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000176 close("Client does not support desktop resize");
177 return;
178 }
179 }
180 }
181 // Just update the whole screen at the moment because we're too lazy to
182 // work out what's actually changed.
183 updates.clear();
184 updates.add_changed(server->pb->getRect());
185 vlog.debug("pixel buffer changed - re-initialising image getter");
186 image_getter.init(server->pb, cp.pf(), writer());
187 if (writer()->needFakeUpdate())
188 writeFramebufferUpdate();
189 } catch(rdr::Exception &e) {
190 close(e.str());
191 }
192}
193
Pierre Ossman04e62db2009-03-23 16:57:07 +0000194void VNCSConnectionST::screenLayoutChange(rdr::U16 reason)
195{
196 try {
197 if (!authenticated())
198 return;
199
200 cp.screenLayout = server->screenLayout;
201 if (state() == RFBSTATE_NORMAL) {
202 writer()->writeExtendedDesktopSize(reason, 0, cp.width, cp.height,
203 cp.screenLayout);
204 }
205
206 if (writer()->needFakeUpdate())
207 writeFramebufferUpdate();
208 } catch(rdr::Exception &e) {
209 close(e.str());
210 }
211}
212
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000213void VNCSConnectionST::setColourMapEntriesOrClose(int firstColour,int nColours)
214{
215 try {
216 setColourMapEntries(firstColour, nColours);
217 } catch(rdr::Exception& e) {
218 close(e.str());
219 }
220}
221
222void VNCSConnectionST::bell()
223{
224 try {
225 if (state() == RFBSTATE_NORMAL) writer()->writeBell();
226 } catch(rdr::Exception& e) {
227 close(e.str());
228 }
229}
230
231void VNCSConnectionST::serverCutText(const char *str, int len)
232{
233 try {
234 if (!(accessRights & AccessCutText)) return;
235 if (!rfb::Server::sendCutText) return;
236 if (state() == RFBSTATE_NORMAL)
237 writer()->writeServerCutText(str, len);
238 } catch(rdr::Exception& e) {
239 close(e.str());
240 }
241}
242
Peter Ã…strandc39e0782009-01-15 12:21:42 +0000243
244void VNCSConnectionST::setDesktopName(const char *name)
245{
246 cp.setName(name);
247 try {
248 if (state() == RFBSTATE_NORMAL) {
249 if (!writer()->writeSetDesktopName()) {
250 fprintf(stderr, "Client does not support desktop rename\n");
251 }
252 }
253 } catch(rdr::Exception& e) {
254 close(e.str());
255 }
256}
257
258
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000259void VNCSConnectionST::setCursorOrClose()
260{
261 try {
262 setCursor();
263 } catch(rdr::Exception& e) {
264 close(e.str());
265 }
266}
267
268
269int VNCSConnectionST::checkIdleTimeout()
270{
271 int idleTimeout = rfb::Server::idleTimeout;
272 if (idleTimeout == 0) return 0;
273 if (state() != RFBSTATE_NORMAL && idleTimeout < 15)
274 idleTimeout = 15; // minimum of 15 seconds while authenticating
275 time_t now = time(0);
276 if (now < lastEventTime) {
277 // Someone must have set the time backwards. Set lastEventTime so that the
278 // idleTimeout will count from now.
279 vlog.info("Time has gone backwards - resetting idle timeout");
280 lastEventTime = now;
281 }
282 int timeLeft = lastEventTime + idleTimeout - now;
283 if (timeLeft < -60) {
284 // Our callback is over a minute late - someone must have set the time
285 // forwards. Set lastEventTime so that the idleTimeout will count from
286 // now.
287 vlog.info("Time has gone forwards - resetting idle timeout");
288 lastEventTime = now;
289 return secsToMillis(idleTimeout);
290 }
291 if (timeLeft <= 0) {
292 close("Idle timeout");
293 return 0;
294 }
295 return secsToMillis(timeLeft);
296}
297
298// renderedCursorChange() is called whenever the server-side rendered cursor
299// changes shape or position. It ensures that the next update will clean up
300// the old rendered cursor and if necessary draw the new rendered cursor.
301
302void VNCSConnectionST::renderedCursorChange()
303{
304 if (state() != RFBSTATE_NORMAL) return;
305 removeRenderedCursor = true;
306 if (needRenderedCursor())
307 drawRenderedCursor = true;
308}
309
310// needRenderedCursor() returns true if this client needs the server-side
311// rendered cursor. This may be because it does not support local cursor or
312// because the current cursor position has not been set by this client.
313// Unfortunately we can't know for sure when the current cursor position has
314// been set by this client. We guess that this is the case when the current
315// cursor position is the same as the last pointer event from this client, or
316// if it is a very short time since this client's last pointer event (up to a
317// second). [ Ideally we should do finer-grained timing here and make the time
318// configurable, but I don't think it's that important. ]
319
320bool VNCSConnectionST::needRenderedCursor()
321{
322 return (state() == RFBSTATE_NORMAL
323 && (!cp.supportsLocalCursor && !cp.supportsLocalXCursor
324 || (!server->cursorPos.equals(pointerEventPos) &&
325 (time(0) - pointerEventTime) > 0)));
326}
327
328
329void VNCSConnectionST::approveConnectionOrClose(bool accept,
330 const char* reason)
331{
332 try {
333 approveConnection(accept, reason);
334 } catch (rdr::Exception& e) {
335 close(e.str());
336 }
337}
338
339
340
341// -=- Callbacks from SConnection
342
343void VNCSConnectionST::authSuccess()
344{
345 lastEventTime = time(0);
346
347 server->startDesktop();
348
349 // - Set the connection parameters appropriately
350 cp.width = server->pb->width();
351 cp.height = server->pb->height();
Pierre Ossman34e62f32009-03-20 21:46:12 +0000352 cp.screenLayout = server->screenLayout;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000353 cp.setName(server->getName());
354
355 // - Set the default pixel format
356 cp.setPF(server->pb->getPF());
357 char buffer[256];
358 cp.pf().print(buffer, 256);
359 vlog.info("Server default pixel format %s", buffer);
360 image_getter.init(server->pb, cp.pf(), 0);
361
362 // - Mark the entire display as "dirty"
363 updates.add_changed(server->pb->getRect());
364 startTime = time(0);
365}
366
367void VNCSConnectionST::queryConnection(const char* userName)
368{
369 // - Authentication succeeded - clear from blacklist
370 CharArray name; name.buf = sock->getPeerAddress();
371 server->blHosts->clearBlackmark(name.buf);
372
373 // - Special case to provide a more useful error message
374 if (rfb::Server::neverShared && !rfb::Server::disconnectClients &&
375 server->authClientCount() > 0) {
376 approveConnection(false, "The server is already in use");
377 return;
378 }
379
380 // - Does the client have the right to bypass the query?
381 if (reverseConnection ||
382 !(rfb::Server::queryConnect || sock->requiresQuery()) ||
383 (accessRights & AccessNoQuery))
384 {
385 approveConnection(true);
386 return;
387 }
388
389 // - Get the server to display an Accept/Reject dialog, if required
390 // If a dialog is displayed, the result will be PENDING, and the
391 // server will call approveConnection at a later time
392 CharArray reason;
393 VNCServerST::queryResult qr = server->queryConnection(sock, userName,
394 &reason.buf);
395 if (qr == VNCServerST::PENDING)
396 return;
397
398 // - If server returns ACCEPT/REJECT then pass result to SConnection
399 approveConnection(qr == VNCServerST::ACCEPT, reason.buf);
400}
401
402void VNCSConnectionST::clientInit(bool shared)
403{
404 lastEventTime = time(0);
405 if (rfb::Server::alwaysShared || reverseConnection) shared = true;
406 if (rfb::Server::neverShared) shared = false;
407 if (!shared) {
408 if (rfb::Server::disconnectClients) {
409 // - Close all the other connected clients
410 vlog.debug("non-shared connection - closing clients");
411 server->closeClients("Non-shared connection requested", getSock());
412 } else {
413 // - Refuse this connection if there are existing clients, in addition to
414 // this one
415 if (server->authClientCount() > 1) {
416 close("Server is already in use");
417 return;
418 }
419 }
420 }
421 SConnection::clientInit(shared);
422}
423
424void VNCSConnectionST::setPixelFormat(const PixelFormat& pf)
425{
426 SConnection::setPixelFormat(pf);
427 char buffer[256];
428 pf.print(buffer, 256);
429 vlog.info("Client pixel format %s", buffer);
430 image_getter.init(server->pb, pf, writer());
431 setCursor();
432}
433
434void VNCSConnectionST::pointerEvent(const Point& pos, int buttonMask)
435{
436 pointerEventTime = lastEventTime = time(0);
437 server->lastUserInputTime = lastEventTime;
438 if (!(accessRights & AccessPtrEvents)) return;
439 if (!rfb::Server::acceptPointerEvents) return;
440 if (!server->pointerClient || server->pointerClient == this) {
441 pointerEventPos = pos;
442 if (buttonMask)
443 server->pointerClient = this;
444 else
445 server->pointerClient = 0;
446 server->desktop->pointerEvent(pointerEventPos, buttonMask);
447 }
448}
449
450
451class VNCSConnectionSTShiftPresser {
452public:
453 VNCSConnectionSTShiftPresser(SDesktop* desktop_)
454 : desktop(desktop_), pressed(false) {}
455 ~VNCSConnectionSTShiftPresser() {
456 if (pressed) { desktop->keyEvent(XK_Shift_L, false); }
457 }
458 void press() {
459 desktop->keyEvent(XK_Shift_L, true);
460 pressed = true;
461 }
462 SDesktop* desktop;
463 bool pressed;
464};
465
466// keyEvent() - record in the pressedKeys which keys were pressed. Allow
467// multiple down events (for autorepeat), but only allow a single up event.
468void VNCSConnectionST::keyEvent(rdr::U32 key, bool down) {
469 lastEventTime = time(0);
470 server->lastUserInputTime = lastEventTime;
471 if (!(accessRights & AccessKeyEvents)) return;
472 if (!rfb::Server::acceptKeyEvents) return;
473
474 // Remap the key if required
475 if (server->keyRemapper)
476 key = server->keyRemapper->remapKey(key);
477
478 // Turn ISO_Left_Tab into shifted Tab.
479 VNCSConnectionSTShiftPresser shiftPresser(server->desktop);
480 if (key == XK_ISO_Left_Tab) {
481 if (pressedKeys.find(XK_Shift_L) == pressedKeys.end() &&
482 pressedKeys.find(XK_Shift_R) == pressedKeys.end())
483 shiftPresser.press();
484 key = XK_Tab;
485 }
486
487 if (down) {
488 pressedKeys.insert(key);
489 } else {
490 if (!pressedKeys.erase(key)) return;
491 }
492 server->desktop->keyEvent(key, down);
493}
494
495void VNCSConnectionST::clientCutText(const char* str, int len)
496{
497 if (!(accessRights & AccessCutText)) return;
498 if (!rfb::Server::acceptCutText) return;
499 server->desktop->clientCutText(str, len);
500}
501
502void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental)
503{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000504 Rect safeRect;
505
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000506 if (!(accessRights & AccessView)) return;
507
508 SConnection::framebufferUpdateRequest(r, incremental);
509
Pierre Ossmane9962f72009-04-23 12:31:42 +0000510 vlog.info("FramebufferUpdateRequest %dx%d at %d,%d %sincr",
511 r.width(), r.height(), r.tl.x, r.tl.y, incremental ? "" : "non-");
512
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000513 // Check that the client isn't sending crappy requests
514 if (!r.enclosed_by(Rect(0, 0, cp.width, cp.height))) {
515 vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d",
516 r.width(), r.height(), r.tl.x, r.tl.y, cp.width, cp.height);
Pierre Ossmane9962f72009-04-23 12:31:42 +0000517 safeRect = r.intersect(Rect(0, 0, cp.width, cp.height));
518 } else {
519 safeRect = r;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000520 }
521
Constantin Kaplinsky2ef66952008-08-29 11:33:46 +0000522 // Just update the requested region.
523 // Framebuffer update will be sent a bit later, see processMessages().
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000524 Region reqRgn(r);
525 requested.assign_union(reqRgn);
526
527 if (!incremental) {
528 // Non-incremental update - treat as if area requested has changed
529 updates.add_changed(reqRgn);
530 server->comparer->add_changed(reqRgn);
Pierre Ossman53125a72009-04-22 15:37:51 +0000531
532 // And send the screen layout to the client (which, unlike the
533 // framebuffer dimensions, the client doesn't get during init)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000534 writer()->writeExtendedDesktopSize();
Pierre Ossman53125a72009-04-22 15:37:51 +0000535
536 // We do not send a DesktopSize since it only contains the
537 // framebuffer size (which the client already should know) and
538 // because some clients don't handle extra DesktopSize events
539 // very well.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000540 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000541}
542
Pierre Ossman34bb0612009-03-21 21:16:14 +0000543void VNCSConnectionST::setDesktopSize(int fb_width, int fb_height,
544 const ScreenSet& layout)
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000545{
Pierre Ossman04e62db2009-03-23 16:57:07 +0000546 unsigned int result;
547
548 // Don't bother the desktop with an invalid configuration
549 if (!layout.validate(fb_width, fb_height)) {
550 writer()->writeExtendedDesktopSize(reasonClient, resultInvalid,
551 fb_width, fb_height, layout);
552 if (writer()->needFakeUpdate())
553 writeFramebufferUpdate();
554 return;
555 }
556
557 // FIXME: the desktop will call back to VNCServerST and an extra set
558 // of ExtendedDesktopSize messages will be sent. This is okay
559 // protocol-wise, but unnecessary.
560 result = server->desktop->setScreenLayout(fb_width, fb_height, layout);
561
562 // Always send back a reply to the requesting client
563 writer()->writeExtendedDesktopSize(reasonClient, result,
564 fb_width, fb_height, layout);
565 if (writer()->needFakeUpdate())
566 writeFramebufferUpdate();
567
568 // But only notify other clients on success
569 if (result == resultSuccess) {
570 if (server->screenLayout != layout)
571 throw Exception("Desktop configured a different screen layout than requested");
572 server->notifyScreenLayoutChange(this);
573 }
Pierre Ossmanc5e25602009-03-20 12:59:05 +0000574}
575
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000576void VNCSConnectionST::setInitialColourMap()
577{
578 setColourMapEntries(0, 0);
579}
580
581// supportsLocalCursor() is called whenever the status of
582// cp.supportsLocalCursor has changed. If the client does now support local
583// cursor, we make sure that the old server-side rendered cursor is cleaned up
584// and the cursor is sent to the client.
585
586void VNCSConnectionST::supportsLocalCursor()
587{
588 if (cp.supportsLocalCursor || cp.supportsLocalXCursor) {
589 removeRenderedCursor = true;
590 drawRenderedCursor = false;
591 setCursor();
592 }
593}
594
595void VNCSConnectionST::writeSetCursorCallback()
596{
597 if (cp.supportsLocalXCursor) {
598 Pixel pix0, pix1;
599 rdr::U8Array bitmap(server->cursor.getBitmap(&pix0, &pix1));
600 if (bitmap.buf) {
601 // The client supports XCursor and the cursor only has two
602 // colors. Use the XCursor encoding.
603 writer()->writeSetXCursor(server->cursor.width(),
604 server->cursor.height(),
605 server->cursor.hotspot.x,
606 server->cursor.hotspot.y,
607 bitmap.buf, server->cursor.mask.buf);
608 return;
609 } else {
610 // More than two colors
611 if (!cp.supportsLocalCursor) {
612 // FIXME: We could reduce to two colors.
613 vlog.info("Unable to send multicolor cursor: RichCursor not supported by client");
614 return;
615 }
616 }
617 }
618
619 // Use RichCursor
620 rdr::U8* transData = writer()->getImageBuf(server->cursor.area());
621 image_getter.translatePixels(server->cursor.data, transData,
622 server->cursor.area());
623 writer()->writeSetCursor(server->cursor.width(),
624 server->cursor.height(),
625 server->cursor.hotspot,
626 transData, server->cursor.mask.buf);
627}
628
629
630void VNCSConnectionST::writeFramebufferUpdate()
631{
Pierre Ossmane9962f72009-04-23 12:31:42 +0000632 if (state() != RFBSTATE_NORMAL || requested.is_empty())
633 return;
Pierre Ossmand9a59ba2009-03-20 15:55:37 +0000634
Pierre Ossmane9962f72009-04-23 12:31:42 +0000635 // First take care of any updates that cannot contain framebuffer data
636 // changes.
637 if (writer()->needNoDataUpdate()) {
638 writer()->writeNoDataUpdate();
639 requested.clear();
640 return;
641 }
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000642
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000643 updates.enable_copyrect(cp.useCopyRect);
644
Pierre Ossman02e43d72009-03-05 11:57:11 +0000645 server->checkUpdate();
Constantin Kaplinskya09dc142008-12-18 12:08:15 +0000646
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000647 // Get the lists of updates. Prior to exporting the data to the `ui' object,
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000648 // getUpdateInfo() will normalize the `updates' object such way that its
Pierre Ossman02e43d72009-03-05 11:57:11 +0000649 // `changed' and `copied' regions would not intersect.
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000650
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000651 UpdateInfo ui;
652 updates.getUpdateInfo(&ui, requested);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000653 bool needNewUpdateInfo = false;
654
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000655 // If the previous position of the rendered cursor overlaps the source of the
656 // copy, then when the copy happens the corresponding rectangle in the
657 // destination will be wrong, so add it to the changed region.
658
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000659 if (!ui.copied.is_empty() && !renderedCursorRect.is_empty()) {
660 Rect bogusCopiedCursor = (renderedCursorRect.translate(ui.copy_delta)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000661 .intersect(server->pb->getRect()));
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000662 if (!ui.copied.intersect(bogusCopiedCursor).is_empty()) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000663 updates.add_changed(bogusCopiedCursor);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000664 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000665 }
666 }
667
668 // If we need to remove the old rendered cursor, just add the rectangle to
669 // the changed region.
670
671 if (removeRenderedCursor) {
672 updates.add_changed(renderedCursorRect);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000673 needNewUpdateInfo = true;
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000674 renderedCursorRect.clear();
675 removeRenderedCursor = false;
676 }
677
678 // Return if there is nothing to send the client.
679
680 if (updates.is_empty() && !writer()->needFakeUpdate() && !drawRenderedCursor)
681 return;
682
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000683 // The `updates' object could change, make sure we have valid update info.
684
685 if (needNewUpdateInfo)
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000686 updates.getUpdateInfo(&ui, requested);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000687
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000688 // If the client needs a server-side rendered cursor, work out the cursor
689 // rectangle. If it's empty then don't bother drawing it, but if it overlaps
690 // with the update region, we need to draw the rendered cursor regardless of
691 // whether it has changed.
692
693 if (needRenderedCursor()) {
694 renderedCursorRect
695 = (server->renderedCursor.getRect(server->renderedCursorTL)
696 .intersect(requested.get_bounding_rect()));
697
698 if (renderedCursorRect.is_empty()) {
699 drawRenderedCursor = false;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000700 } else if (!ui.changed.union_(ui.copied)
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000701 .intersect(renderedCursorRect).is_empty()) {
702 drawRenderedCursor = true;
703 }
704
705 // We could remove the new cursor rect from updates here. It's not clear
706 // whether this is worth it. If we do remove it, then we won't draw over
707 // the same bit of screen twice, but we have the overhead of a more complex
708 // region.
709
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000710 //if (drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000711 // updates.subtract(renderedCursorRect);
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000712 // updates.getUpdateInfo(&ui, requested);
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000713 //}
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000714 }
715
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000716 if (!ui.is_empty() || writer()->needFakeUpdate() || drawRenderedCursor) {
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000717 // Compute the number of rectangles. Tight encoder makes the things more
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000718 // complicated as compared to the original VNC4.
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000719 writer()->setupCurrentEncoder();
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000720 int nRects = (ui.copied.numRects() +
Constantin Kaplinsky1a845d02007-08-31 21:06:53 +0000721 (drawRenderedCursor ? 1 : 0));
Constantin Kaplinsky651606d2007-10-17 17:40:23 +0000722
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000723 std::vector<Rect> rects;
724 std::vector<Rect>::const_iterator i;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000725 ui.changed.get_rects(&rects);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000726 for (i = rects.begin(); i != rects.end(); i++) {
727 if (i->width() && i->height())
Constantin Kaplinsky604d7812007-08-31 15:50:37 +0000728 nRects += writer()->getNumRects(*i);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000729 }
730
731 writer()->writeFramebufferUpdateStart(nRects);
732 Region updatedRegion;
Constantin Kaplinsky45517c82007-08-31 15:56:33 +0000733 writer()->writeRects(ui, &image_getter, &updatedRegion);
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000734 updates.subtract(updatedRegion);
735 if (drawRenderedCursor)
736 writeRenderedCursorRect();
737 writer()->writeFramebufferUpdateEnd();
Constantin Kaplinskya2adc8d2006-05-25 05:01:55 +0000738 requested.clear();
739 }
740}
741
742
743// writeRenderedCursorRect() writes a single rectangle drawing the rendered
744// cursor on the client.
745
746void VNCSConnectionST::writeRenderedCursorRect()
747{
748 image_getter.setPixelBuffer(&server->renderedCursor);
749 image_getter.setOffset(server->renderedCursorTL);
750
751 Rect actual;
752 writer()->writeRect(renderedCursorRect, &image_getter, &actual);
753
754 image_getter.setPixelBuffer(server->pb);
755 image_getter.setOffset(Point(0,0));
756
757 drawRenderedCursor = false;
758}
759
760void VNCSConnectionST::setColourMapEntries(int firstColour, int nColours)
761{
762 if (!readyForSetColourMapEntries) return;
763 if (server->pb->getPF().trueColour) return;
764
765 image_getter.setColourMapEntries(firstColour, nColours, writer());
766
767 if (cp.pf().trueColour) {
768 updates.add_changed(server->pb->getRect());
769 }
770}
771
772
773// setCursor() is called whenever the cursor has changed shape or pixel format.
774// If the client supports local cursor then it will arrange for the cursor to
775// be sent to the client.
776
777void VNCSConnectionST::setCursor()
778{
779 if (state() != RFBSTATE_NORMAL || !cp.supportsLocalCursor) return;
780 writer()->cursorChange(this);
781 if (writer()->needFakeUpdate())
782 writeFramebufferUpdate();
783}
784
785void VNCSConnectionST::setSocketTimeouts()
786{
787 int timeoutms = rfb::Server::clientWaitTimeMillis;
788 soonestTimeout(&timeoutms, secsToMillis(rfb::Server::idleTimeout));
789 if (timeoutms == 0)
790 timeoutms = -1;
791 sock->inStream().setTimeout(timeoutms);
792 sock->outStream().setTimeout(timeoutms);
793}
794
795char* VNCSConnectionST::getStartTime()
796{
797 char* result = ctime(&startTime);
798 result[24] = '\0';
799 return result;
800}
801
802void VNCSConnectionST::setStatus(int status)
803{
804 switch (status) {
805 case 0:
806 accessRights = accessRights | AccessPtrEvents | AccessKeyEvents | AccessView;
807 break;
808 case 1:
809 accessRights = accessRights & !(AccessPtrEvents | AccessKeyEvents) | AccessView;
810 break;
811 case 2:
812 accessRights = accessRights & !(AccessPtrEvents | AccessKeyEvents | AccessView);
813 break;
814 }
815 framebufferUpdateRequest(server->pb->getRect(), false);
816}
817int VNCSConnectionST::getStatus()
818{
819 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0007)
820 return 0;
821 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0001)
822 return 1;
823 if ((accessRights & (AccessPtrEvents | AccessKeyEvents | AccessView)) == 0x0000)
824 return 2;
825 return 4;
826}
827