blob: 3d3d582df84802912d7f38027f32f9b17e3ef010 [file] [log] [blame]
Pierre Ossman5156d5e2011-03-09 09:42:34 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 * Copyright 2009-2011 Pierre Ossman <ossman@cendio.se> for Cendio AB
DRC33c15e32011-11-03 18:49:21 +00003 * Copyright (C) 2011 D. R. Commander. All Rights Reserved.
Pierre Ossman5156d5e2011-03-09 09:42:34 +00004 *
5 * This is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This software is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this software; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
18 * USA.
19 */
20
Peter Åstrandc359f362011-08-23 12:04:46 +000021#ifdef HAVE_CONFIG_H
22#include <config.h>
23#endif
24
Pierre Ossman5156d5e2011-03-09 09:42:34 +000025#include <assert.h>
DRCb65bb932011-06-24 03:17:00 +000026#ifndef _WIN32
Pierre Ossman5156d5e2011-03-09 09:42:34 +000027#include <unistd.h>
DRCb65bb932011-06-24 03:17:00 +000028#endif
Pierre Ossman5156d5e2011-03-09 09:42:34 +000029
30#include <rfb/CMsgWriter.h>
31#include <rfb/encodings.h>
32#include <rfb/Hostname.h>
33#include <rfb/LogWriter.h>
34#include <rfb/util.h>
35#include <rfb/screenTypes.h>
36#include <rfb/Timer.h>
37#include <network/TcpSocket.h>
38
39#include <FL/Fl.H>
40#include <FL/fl_ask.H>
41
42#include "CConn.h"
Pierre Ossmanf4f30942011-05-17 09:39:07 +000043#include "OptionsDialog.h"
Pierre Ossman5156d5e2011-03-09 09:42:34 +000044#include "i18n.h"
45#include "parameters.h"
Pierre Ossman39ceb502011-07-12 15:54:25 +000046#include "vncviewer.h"
Pierre Ossman5156d5e2011-03-09 09:42:34 +000047
DRCb65bb932011-06-24 03:17:00 +000048#ifdef WIN32
49#include "win32.h"
50#endif
51
Pierre Ossman5156d5e2011-03-09 09:42:34 +000052using namespace rdr;
53using namespace rfb;
54using namespace std;
55
Pierre Ossman5156d5e2011-03-09 09:42:34 +000056static rfb::LogWriter vlog("CConn");
57
Pierre Ossmancf836f22011-07-14 14:34:09 +000058// 8 colours (1 bit per component)
59static const PixelFormat verylowColourPF(8, 3,false, true,
60 1, 1, 1, 2, 1, 0);
61// 64 colours (2 bits per component)
62static const PixelFormat lowColourPF(8, 6, false, true,
63 3, 3, 3, 4, 2, 0);
64// 256 colours (palette)
65static const PixelFormat mediumColourPF(8, 8, false, false);
Pierre Ossmanf4f30942011-05-17 09:39:07 +000066
Pierre Ossman5156d5e2011-03-09 09:42:34 +000067CConn::CConn(const char* vncServerName)
68 : serverHost(0), serverPort(0), sock(NULL), desktop(NULL),
69 currentEncoding(encodingTight), lastServerEncoding((unsigned int)-1),
70 formatChange(false), encodingChange(false),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +000071 firstUpdate(true), pendingUpdate(false),
Pierre Ossmanfba3e862011-07-15 13:45:19 +000072 forceNonincremental(true)
Pierre Ossman5156d5e2011-03-09 09:42:34 +000073{
74 setShared(::shared);
75
76 int encNum = encodingNum(preferredEncoding);
77 if (encNum != -1)
78 currentEncoding = encNum;
79
Pierre Ossmanda389562011-06-09 08:24:37 +000080 cp.supportsLocalCursor = true;
81
Pierre Ossman5156d5e2011-03-09 09:42:34 +000082 cp.supportsDesktopResize = true;
83 cp.supportsExtendedDesktopSize = true;
84 cp.supportsDesktopRename = true;
Pierre Ossman5156d5e2011-03-09 09:42:34 +000085
86 cp.customCompressLevel = customCompressLevel;
87 cp.compressLevel = compressLevel;
88
89 cp.noJpeg = noJpeg;
90 cp.qualityLevel = qualityLevel;
91
92 try {
93 getHostAndPort(vncServerName, &serverHost, &serverPort);
94
95 sock = new network::TcpSocket(serverHost, serverPort);
96 vlog.info(_("connected to host %s port %d"), serverHost, serverPort);
97 } catch (rdr::Exception& e) {
98 vlog.error(e.str());
99 fl_alert(e.str());
100 exit_vncviewer();
101 return;
102 }
103
104 Fl::add_fd(sock->getFd(), FL_READ | FL_EXCEPT, socketEvent, this);
105
106 // See callback below
107 sock->inStream().setBlockCallback(this);
108
109 setServerName(serverHost);
110 setStreams(&sock->inStream(), &sock->outStream());
111
112 initialiseProtocol();
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000113
114 OptionsDialog::addCallback(handleOptions, this);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000115}
116
117CConn::~CConn()
118{
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000119 OptionsDialog::removeCallback(handleOptions);
120
Pierre Ossman6a9e2e62011-05-19 14:47:43 +0000121 if (desktop)
122 delete desktop;
123
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000124 free(serverHost);
125 if (sock)
126 Fl::remove_fd(sock->getFd());
127 delete sock;
128}
129
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000130void CConn::refreshFramebuffer()
131{
132 // FIXME: We cannot safely trigger an update request directly but must
133 // wait for the next update to arrive.
134 if (!formatChange)
135 forceNonincremental = true;
136}
137
Pierre Ossman2eb1d112011-05-16 12:18:08 +0000138const char *CConn::connectionInfo()
139{
140 static char infoText[1024] = "";
141
142 char pfStr[100];
143 char spfStr[100];
144
145 cp.pf().print(pfStr, 100);
146 serverPF.print(spfStr, 100);
147
148 int secType = csecurity->getType();
149
150 snprintf(infoText, sizeof(infoText),
151 _("Desktop name: %.80s\n"
152 "Host: %.80s port: %d\n"
153 "Size: %d x %d\n"
154 "Pixel format: %s\n"
155 "(server default %s)\n"
156 "Requested encoding: %s\n"
157 "Last used encoding: %s\n"
158 "Line speed estimate: %d kbit/s\n"
159 "Protocol version: %d.%d\n"
160 "Security method: %s\n"),
161 cp.name(), serverHost, serverPort, cp.width, cp.height,
162 pfStr, spfStr, encodingName(currentEncoding),
163 encodingName(lastServerEncoding),
164 sock->inStream().kbitsPerSecond(),
165 cp.majorVersion, cp.minorVersion,
166 secTypeName(secType));
167
168 return infoText;
169}
170
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000171// The RFB core is not properly asynchronous, so it calls this callback
172// whenever it needs to block to wait for more data. Since FLTK is
173// monitoring the socket, we just make sure FLTK gets to run.
174
175void CConn::blockCallback()
176{
177 int next_timer;
178
179 next_timer = Timer::checkTimeouts();
180 if (next_timer == 0)
181 next_timer = INT_MAX;
182
183 Fl::wait((double)next_timer / 1000.0);
184}
185
186void CConn::socketEvent(int fd, void *data)
187{
188 CConn *cc;
189 static bool recursing = false;
190
191 assert(data);
192 cc = (CConn*)data;
193
194 // I don't think processMsg() is recursion safe, so add this check
195 if (recursing)
196 return;
197
198 recursing = true;
199
200 try {
201 // processMsg() only processes one message, so we need to loop
202 // until the buffers are empty or things will stall.
203 do {
204 cc->processMsg();
205 } while (cc->sock->inStream().checkNoWait(1));
206 } catch (rdr::EndOfStream& e) {
207 vlog.info(e.str());
208 exit_vncviewer();
209 } catch (rdr::Exception& e) {
210 vlog.error(e.str());
Pierre Ossmane2ef5c12011-07-12 16:56:34 +0000211 exit_vncviewer(e.str());
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000212 }
213
214 recursing = false;
215}
216
217////////////////////// CConnection callback methods //////////////////////
218
219// serverInit() is called when the serverInit message has been received. At
220// this point we create the desktop window and display it. We also tell the
221// server the pixel format and encodings to use and request the first update.
222void CConn::serverInit()
223{
224 CConnection::serverInit();
225
226 // If using AutoSelect with old servers, start in FullColor
227 // mode. See comment in autoSelectFormatAndEncoding.
228 if (cp.beforeVersion(3, 8) && autoSelect)
229 fullColour.setParam(true);
230
231 serverPF = cp.pf();
232
233 desktop = new DesktopWindow(cp.width, cp.height, cp.name(), serverPF, this);
234 fullColourPF = desktop->getPreferredPF();
235
236 formatChange = encodingChange = true;
237 requestNewUpdate();
238}
239
240// setDesktopSize() is called when the desktop size changes (including when
241// it is set initially).
242void CConn::setDesktopSize(int w, int h)
243{
244 CConnection::setDesktopSize(w,h);
245 resizeFramebuffer();
246}
247
248// setExtendedDesktopSize() is a more advanced version of setDesktopSize()
249void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
250 const rfb::ScreenSet& layout)
251{
252 CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
253
254 if ((reason == reasonClient) && (result != resultSuccess)) {
255 vlog.error(_("SetDesktopSize failed: %d"), result);
256 return;
257 }
258
259 resizeFramebuffer();
260}
261
262// setName() is called when the desktop name changes
263void CConn::setName(const char* name)
264{
265 CConnection::setName(name);
266 if (desktop)
267 desktop->setName(name);
268}
269
270// framebufferUpdateStart() is called at the beginning of an update.
271// Here we try to send out a new framebuffer update request so that the
272// next update can be sent out in parallel with us decoding the current
273// one. We cannot do this if we're in the middle of a format change
274// though.
275void CConn::framebufferUpdateStart()
276{
277 if (!formatChange) {
278 pendingUpdate = true;
279 requestNewUpdate();
280 } else
281 pendingUpdate = false;
282}
283
284// framebufferUpdateEnd() is called at the end of an update.
285// For each rectangle, the FdInStream will have timed the speed
286// of the connection, allowing us to select format and encoding
287// appropriately, and then request another incremental update.
288void CConn::framebufferUpdateEnd()
289{
290 desktop->updateWindow();
291
292 if (firstUpdate) {
293 int width, height;
294
295 if (cp.supportsSetDesktopSize &&
296 sscanf(desktopSize.getValueStr(), "%dx%d", &width, &height) == 2) {
297 ScreenSet layout;
298
299 layout = cp.screenLayout;
300
301 if (layout.num_screens() == 0)
302 layout.add_screen(rfb::Screen());
303 else if (layout.num_screens() != 1) {
304 ScreenSet::iterator iter;
305
306 while (true) {
307 iter = layout.begin();
308 ++iter;
309
310 if (iter == layout.end())
311 break;
312
313 layout.remove_screen(iter->id);
314 }
315 }
316
317 layout.begin()->dimensions.tl.x = 0;
318 layout.begin()->dimensions.tl.y = 0;
319 layout.begin()->dimensions.br.x = width;
320 layout.begin()->dimensions.br.y = height;
321
322 writer()->writeSetDesktopSize(width, height, layout);
323 }
324
325 firstUpdate = false;
326 }
327
328 // A format change prevented us from sending this before the update,
329 // so make sure to send it now.
330 if (formatChange && !pendingUpdate)
331 requestNewUpdate();
332
333 // Compute new settings based on updated bandwidth values
334 if (autoSelect)
335 autoSelectFormatAndEncoding();
336
337 // Make sure that the FLTK handling and the timers gets some CPU time
338 // in case of back to back framebuffer updates.
339 Fl::check();
340 Timer::checkTimeouts();
341}
342
343// The rest of the callbacks are fairly self-explanatory...
344
345void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
346{
347 desktop->setColourMapEntries(firstColour, nColours, rgbs);
348}
349
350void CConn::bell()
351{
352 fl_beep();
353}
354
355void CConn::serverCutText(const char* str, rdr::U32 len)
356{
Pierre Ossman689c4582011-05-26 15:39:41 +0000357 char *buffer;
358 int size, ret;
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000359
Pierre Ossman689c4582011-05-26 15:39:41 +0000360 size = fl_utf8froma(NULL, 0, str, len);
361 if (size <= 0)
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000362 return;
Pierre Ossman689c4582011-05-26 15:39:41 +0000363
364 size++;
365
366 buffer = new char[size];
367
368 ret = fl_utf8froma(buffer, size, str, len);
369 assert(ret < size);
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000370
371 vlog.debug("Got clipboard data: '%s'", buffer);
372
Pierre Ossmancf2443c2011-09-07 09:01:20 +0000373 // RFB doesn't have separate selection and clipboard concepts, so we
374 // dump the data into both variants.
375 Fl::copy(buffer, ret, 0);
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000376 Fl::copy(buffer, ret, 1);
Pierre Ossman689c4582011-05-26 15:39:41 +0000377
378 delete [] buffer;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000379}
380
381// We start timing on beginRect and stop timing on endRect, to
382// avoid skewing the bandwidth estimation as a result of the server
383// being slow or the network having high latency
384void CConn::beginRect(const Rect& r, int encoding)
385{
386 sock->inStream().startTiming();
387 if (encoding != encodingCopyRect) {
388 lastServerEncoding = encoding;
389 }
390}
391
392void CConn::endRect(const Rect& r, int encoding)
393{
394 sock->inStream().stopTiming();
395}
396
397void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p)
398{
399 desktop->fillRect(r,p);
400}
401void CConn::imageRect(const rfb::Rect& r, void* p)
402{
403 desktop->imageRect(r,p);
404}
405void CConn::copyRect(const rfb::Rect& r, int sx, int sy)
406{
407 desktop->copyRect(r,sx,sy);
408}
409void CConn::setCursor(int width, int height, const Point& hotspot,
410 void* data, void* mask)
411{
Pierre Ossman835b4ef2011-06-08 17:02:36 +0000412 desktop->setCursor(width, height, hotspot, data, mask);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000413}
414
DRC33c15e32011-11-03 18:49:21 +0000415rdr::U8* CConn::getRawPixelsRW(const rfb::Rect& r, int* stride) {
416 return desktop->getPixelsRW(r, stride);
417}
418void CConn::releaseRawPixels(const rfb::Rect& r) {
419 desktop->damageRect(r);
420}
421
422
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000423////////////////////// Internal methods //////////////////////
424
425void CConn::resizeFramebuffer()
426{
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000427 if (!desktop)
428 return;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000429
Pierre Ossman6455d852011-06-01 09:33:00 +0000430 desktop->resizeFramebuffer(cp.width, cp.height);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000431}
432
433// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
434// to the connection speed:
435//
436// First we wait for at least one second of bandwidth measurement.
437//
438// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
439// which should be perceptually lossless.
440//
441// If the bandwidth is below that, we choose a more lossy JPEG quality.
442//
443// If the bandwidth drops below 256 Kbps, we switch to palette mode.
444//
445// Note: The system here is fairly arbitrary and should be replaced
446// with something more intelligent at the server end.
447//
448void CConn::autoSelectFormatAndEncoding()
449{
450 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
451 unsigned int timeWaited = sock->inStream().timeWaited();
452 bool newFullColour = fullColour;
453 int newQualityLevel = qualityLevel;
454
455 // Always use Tight
456 if (currentEncoding != encodingTight) {
457 currentEncoding = encodingTight;
458 encodingChange = true;
459 }
460
461 // Check that we have a decent bandwidth measurement
462 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
463 return;
464
465 // Select appropriate quality level
466 if (!noJpeg) {
467 if (kbitsPerSecond > 16000)
468 newQualityLevel = 8;
469 else
470 newQualityLevel = 6;
471
472 if (newQualityLevel != qualityLevel) {
473 vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
474 kbitsPerSecond, newQualityLevel);
475 cp.qualityLevel = newQualityLevel;
476 qualityLevel.setParam(newQualityLevel);
477 encodingChange = true;
478 }
479 }
480
481 if (cp.beforeVersion(3, 8)) {
482 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
483 // cursors "asynchronously". If this happens in the middle of a
484 // pixel format change, the server will encode the cursor with
485 // the old format, but the client will try to decode it
486 // according to the new format. This will lead to a
487 // crash. Therefore, we do not allow automatic format change for
488 // old servers.
489 return;
490 }
491
492 // Select best color level
493 newFullColour = (kbitsPerSecond > 256);
494 if (newFullColour != fullColour) {
495 vlog.info(_("Throughput %d kbit/s - full color is now %s"),
496 kbitsPerSecond,
497 newFullColour ? _("enabled") : _("disabled"));
498 fullColour.setParam(newFullColour);
499 formatChange = true;
500 }
501}
502
503// checkEncodings() sends a setEncodings message if one is needed.
504void CConn::checkEncodings()
505{
506 if (encodingChange && writer()) {
507 vlog.info(_("Using %s encoding"),encodingName(currentEncoding));
508 writer()->writeSetEncodings(currentEncoding, true);
509 encodingChange = false;
510 }
511}
512
513// requestNewUpdate() requests an update from the server, having set the
514// format and encoding appropriately.
515void CConn::requestNewUpdate()
516{
517 if (formatChange) {
518 PixelFormat pf;
519
520 /* Catch incorrect requestNewUpdate calls */
521 assert(pendingUpdate == false);
522
523 if (fullColour) {
524 pf = fullColourPF;
525 } else {
526 if (lowColourLevel == 0)
Pierre Ossmancf836f22011-07-14 14:34:09 +0000527 pf = verylowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000528 else if (lowColourLevel == 1)
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000529 pf = lowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000530 else
Pierre Ossmancf836f22011-07-14 14:34:09 +0000531 pf = mediumColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000532 }
533 char str[256];
534 pf.print(str, 256);
535 vlog.info(_("Using pixel format %s"),str);
536 desktop->setServerPF(pf);
537 cp.setPF(pf);
538 writer()->writeSetPixelFormat(pf);
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000539
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000540 formatChange = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000541 }
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000542
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000543 checkEncodings();
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000544
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000545 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000546 !forceNonincremental);
547
548 forceNonincremental = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000549}
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000550
551void CConn::handleOptions(void *data)
552{
553 CConn *self = (CConn*)data;
554
555 // Checking all the details of the current set of encodings is just
556 // a pain. Assume something has changed, as resending the encoding
557 // list is cheap. Avoid overriding what the auto logic has selected
558 // though.
559 if (!autoSelect) {
560 int encNum = encodingNum(preferredEncoding);
561
562 if (encNum != -1)
563 self->currentEncoding = encNum;
564
565 self->cp.qualityLevel = qualityLevel;
566 }
567
Pierre Ossmanda389562011-06-09 08:24:37 +0000568 self->cp.supportsLocalCursor = true;
569
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000570 self->cp.customCompressLevel = customCompressLevel;
571 self->cp.compressLevel = compressLevel;
572
573 self->cp.noJpeg = noJpeg;
574
575 self->encodingChange = true;
576
577 // Format changes refreshes the entire screen though and are therefore
578 // very costly. It's probably worth the effort to see if it is necessary
579 // here.
580 PixelFormat pf;
581
582 if (fullColour) {
583 pf = self->fullColourPF;
584 } else {
585 if (lowColourLevel == 0)
Pierre Ossmancf836f22011-07-14 14:34:09 +0000586 pf = verylowColourPF;
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000587 else if (lowColourLevel == 1)
588 pf = lowColourPF;
589 else
Pierre Ossmancf836f22011-07-14 14:34:09 +0000590 pf = mediumColourPF;
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000591 }
592
593 if (!pf.equal(self->cp.pf()))
594 self->formatChange = true;
595}