blob: 5b5be9911781a74ba7dced4a85c3a7e73e442d81 [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
3 *
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 <assert.h>
DRCb65bb932011-06-24 03:17:00 +000021#ifndef _WIN32
Pierre Ossman5156d5e2011-03-09 09:42:34 +000022#include <unistd.h>
DRCb65bb932011-06-24 03:17:00 +000023#endif
Pierre Ossman5156d5e2011-03-09 09:42:34 +000024
25#include <rfb/CMsgWriter.h>
26#include <rfb/encodings.h>
27#include <rfb/Hostname.h>
28#include <rfb/LogWriter.h>
29#include <rfb/util.h>
30#include <rfb/screenTypes.h>
31#include <rfb/Timer.h>
32#include <network/TcpSocket.h>
33
34#include <FL/Fl.H>
35#include <FL/fl_ask.H>
36
37#include "CConn.h"
Pierre Ossmanf4f30942011-05-17 09:39:07 +000038#include "OptionsDialog.h"
Pierre Ossman5156d5e2011-03-09 09:42:34 +000039#include "i18n.h"
40#include "parameters.h"
Pierre Ossman39ceb502011-07-12 15:54:25 +000041#include "vncviewer.h"
Pierre Ossman5156d5e2011-03-09 09:42:34 +000042
DRCb65bb932011-06-24 03:17:00 +000043#ifdef WIN32
44#include "win32.h"
45#endif
46
Pierre Ossman5156d5e2011-03-09 09:42:34 +000047using namespace rdr;
48using namespace rfb;
49using namespace std;
50
Pierre Ossman5156d5e2011-03-09 09:42:34 +000051static rfb::LogWriter vlog("CConn");
52
Pierre Ossmancf836f22011-07-14 14:34:09 +000053// 8 colours (1 bit per component)
54static const PixelFormat verylowColourPF(8, 3,false, true,
55 1, 1, 1, 2, 1, 0);
56// 64 colours (2 bits per component)
57static const PixelFormat lowColourPF(8, 6, false, true,
58 3, 3, 3, 4, 2, 0);
59// 256 colours (palette)
60static const PixelFormat mediumColourPF(8, 8, false, false);
Pierre Ossmanf4f30942011-05-17 09:39:07 +000061
Pierre Ossman5156d5e2011-03-09 09:42:34 +000062CConn::CConn(const char* vncServerName)
63 : serverHost(0), serverPort(0), sock(NULL), desktop(NULL),
64 currentEncoding(encodingTight), lastServerEncoding((unsigned int)-1),
65 formatChange(false), encodingChange(false),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +000066 firstUpdate(true), pendingUpdate(false),
67 forceNonincremental(false)
Pierre Ossman5156d5e2011-03-09 09:42:34 +000068{
69 setShared(::shared);
70
71 int encNum = encodingNum(preferredEncoding);
72 if (encNum != -1)
73 currentEncoding = encNum;
74
Pierre Ossmanda389562011-06-09 08:24:37 +000075 cp.supportsLocalCursor = true;
76
Pierre Ossman5156d5e2011-03-09 09:42:34 +000077 cp.supportsDesktopResize = true;
78 cp.supportsExtendedDesktopSize = true;
79 cp.supportsDesktopRename = true;
Pierre Ossman5156d5e2011-03-09 09:42:34 +000080
81 cp.customCompressLevel = customCompressLevel;
82 cp.compressLevel = compressLevel;
83
84 cp.noJpeg = noJpeg;
85 cp.qualityLevel = qualityLevel;
86
87 try {
88 getHostAndPort(vncServerName, &serverHost, &serverPort);
89
90 sock = new network::TcpSocket(serverHost, serverPort);
91 vlog.info(_("connected to host %s port %d"), serverHost, serverPort);
92 } catch (rdr::Exception& e) {
93 vlog.error(e.str());
94 fl_alert(e.str());
95 exit_vncviewer();
96 return;
97 }
98
99 Fl::add_fd(sock->getFd(), FL_READ | FL_EXCEPT, socketEvent, this);
100
101 // See callback below
102 sock->inStream().setBlockCallback(this);
103
104 setServerName(serverHost);
105 setStreams(&sock->inStream(), &sock->outStream());
106
107 initialiseProtocol();
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000108
109 OptionsDialog::addCallback(handleOptions, this);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000110}
111
112CConn::~CConn()
113{
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000114 OptionsDialog::removeCallback(handleOptions);
115
Pierre Ossman6a9e2e62011-05-19 14:47:43 +0000116 if (desktop)
117 delete desktop;
118
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000119 free(serverHost);
120 if (sock)
121 Fl::remove_fd(sock->getFd());
122 delete sock;
123}
124
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000125void CConn::refreshFramebuffer()
126{
127 // FIXME: We cannot safely trigger an update request directly but must
128 // wait for the next update to arrive.
129 if (!formatChange)
130 forceNonincremental = true;
131}
132
Pierre Ossman2eb1d112011-05-16 12:18:08 +0000133const char *CConn::connectionInfo()
134{
135 static char infoText[1024] = "";
136
137 char pfStr[100];
138 char spfStr[100];
139
140 cp.pf().print(pfStr, 100);
141 serverPF.print(spfStr, 100);
142
143 int secType = csecurity->getType();
144
145 snprintf(infoText, sizeof(infoText),
146 _("Desktop name: %.80s\n"
147 "Host: %.80s port: %d\n"
148 "Size: %d x %d\n"
149 "Pixel format: %s\n"
150 "(server default %s)\n"
151 "Requested encoding: %s\n"
152 "Last used encoding: %s\n"
153 "Line speed estimate: %d kbit/s\n"
154 "Protocol version: %d.%d\n"
155 "Security method: %s\n"),
156 cp.name(), serverHost, serverPort, cp.width, cp.height,
157 pfStr, spfStr, encodingName(currentEncoding),
158 encodingName(lastServerEncoding),
159 sock->inStream().kbitsPerSecond(),
160 cp.majorVersion, cp.minorVersion,
161 secTypeName(secType));
162
163 return infoText;
164}
165
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000166// The RFB core is not properly asynchronous, so it calls this callback
167// whenever it needs to block to wait for more data. Since FLTK is
168// monitoring the socket, we just make sure FLTK gets to run.
169
170void CConn::blockCallback()
171{
172 int next_timer;
173
174 next_timer = Timer::checkTimeouts();
175 if (next_timer == 0)
176 next_timer = INT_MAX;
177
178 Fl::wait((double)next_timer / 1000.0);
179}
180
181void CConn::socketEvent(int fd, void *data)
182{
183 CConn *cc;
184 static bool recursing = false;
185
186 assert(data);
187 cc = (CConn*)data;
188
189 // I don't think processMsg() is recursion safe, so add this check
190 if (recursing)
191 return;
192
193 recursing = true;
194
195 try {
196 // processMsg() only processes one message, so we need to loop
197 // until the buffers are empty or things will stall.
198 do {
199 cc->processMsg();
200 } while (cc->sock->inStream().checkNoWait(1));
201 } catch (rdr::EndOfStream& e) {
202 vlog.info(e.str());
203 exit_vncviewer();
204 } catch (rdr::Exception& e) {
205 vlog.error(e.str());
Pierre Ossmane2ef5c12011-07-12 16:56:34 +0000206 exit_vncviewer(e.str());
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000207 }
208
209 recursing = false;
210}
211
212////////////////////// CConnection callback methods //////////////////////
213
214// serverInit() is called when the serverInit message has been received. At
215// this point we create the desktop window and display it. We also tell the
216// server the pixel format and encodings to use and request the first update.
217void CConn::serverInit()
218{
219 CConnection::serverInit();
220
221 // If using AutoSelect with old servers, start in FullColor
222 // mode. See comment in autoSelectFormatAndEncoding.
223 if (cp.beforeVersion(3, 8) && autoSelect)
224 fullColour.setParam(true);
225
226 serverPF = cp.pf();
227
228 desktop = new DesktopWindow(cp.width, cp.height, cp.name(), serverPF, this);
229 fullColourPF = desktop->getPreferredPF();
230
231 formatChange = encodingChange = true;
232 requestNewUpdate();
233}
234
235// setDesktopSize() is called when the desktop size changes (including when
236// it is set initially).
237void CConn::setDesktopSize(int w, int h)
238{
239 CConnection::setDesktopSize(w,h);
240 resizeFramebuffer();
241}
242
243// setExtendedDesktopSize() is a more advanced version of setDesktopSize()
244void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
245 const rfb::ScreenSet& layout)
246{
247 CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
248
249 if ((reason == reasonClient) && (result != resultSuccess)) {
250 vlog.error(_("SetDesktopSize failed: %d"), result);
251 return;
252 }
253
254 resizeFramebuffer();
255}
256
257// setName() is called when the desktop name changes
258void CConn::setName(const char* name)
259{
260 CConnection::setName(name);
261 if (desktop)
262 desktop->setName(name);
263}
264
265// framebufferUpdateStart() is called at the beginning of an update.
266// Here we try to send out a new framebuffer update request so that the
267// next update can be sent out in parallel with us decoding the current
268// one. We cannot do this if we're in the middle of a format change
269// though.
270void CConn::framebufferUpdateStart()
271{
272 if (!formatChange) {
273 pendingUpdate = true;
274 requestNewUpdate();
275 } else
276 pendingUpdate = false;
277}
278
279// framebufferUpdateEnd() is called at the end of an update.
280// For each rectangle, the FdInStream will have timed the speed
281// of the connection, allowing us to select format and encoding
282// appropriately, and then request another incremental update.
283void CConn::framebufferUpdateEnd()
284{
285 desktop->updateWindow();
286
287 if (firstUpdate) {
288 int width, height;
289
290 if (cp.supportsSetDesktopSize &&
291 sscanf(desktopSize.getValueStr(), "%dx%d", &width, &height) == 2) {
292 ScreenSet layout;
293
294 layout = cp.screenLayout;
295
296 if (layout.num_screens() == 0)
297 layout.add_screen(rfb::Screen());
298 else if (layout.num_screens() != 1) {
299 ScreenSet::iterator iter;
300
301 while (true) {
302 iter = layout.begin();
303 ++iter;
304
305 if (iter == layout.end())
306 break;
307
308 layout.remove_screen(iter->id);
309 }
310 }
311
312 layout.begin()->dimensions.tl.x = 0;
313 layout.begin()->dimensions.tl.y = 0;
314 layout.begin()->dimensions.br.x = width;
315 layout.begin()->dimensions.br.y = height;
316
317 writer()->writeSetDesktopSize(width, height, layout);
318 }
319
320 firstUpdate = false;
321 }
322
323 // A format change prevented us from sending this before the update,
324 // so make sure to send it now.
325 if (formatChange && !pendingUpdate)
326 requestNewUpdate();
327
328 // Compute new settings based on updated bandwidth values
329 if (autoSelect)
330 autoSelectFormatAndEncoding();
331
332 // Make sure that the FLTK handling and the timers gets some CPU time
333 // in case of back to back framebuffer updates.
334 Fl::check();
335 Timer::checkTimeouts();
336}
337
338// The rest of the callbacks are fairly self-explanatory...
339
340void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
341{
342 desktop->setColourMapEntries(firstColour, nColours, rgbs);
343}
344
345void CConn::bell()
346{
347 fl_beep();
348}
349
350void CConn::serverCutText(const char* str, rdr::U32 len)
351{
Pierre Ossman689c4582011-05-26 15:39:41 +0000352 char *buffer;
353 int size, ret;
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000354
Pierre Ossman689c4582011-05-26 15:39:41 +0000355 size = fl_utf8froma(NULL, 0, str, len);
356 if (size <= 0)
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000357 return;
Pierre Ossman689c4582011-05-26 15:39:41 +0000358
359 size++;
360
361 buffer = new char[size];
362
363 ret = fl_utf8froma(buffer, size, str, len);
364 assert(ret < size);
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000365
366 vlog.debug("Got clipboard data: '%s'", buffer);
367
368 Fl::copy(buffer, ret, 1);
Pierre Ossman689c4582011-05-26 15:39:41 +0000369
370 delete [] buffer;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000371}
372
373// We start timing on beginRect and stop timing on endRect, to
374// avoid skewing the bandwidth estimation as a result of the server
375// being slow or the network having high latency
376void CConn::beginRect(const Rect& r, int encoding)
377{
378 sock->inStream().startTiming();
379 if (encoding != encodingCopyRect) {
380 lastServerEncoding = encoding;
381 }
382}
383
384void CConn::endRect(const Rect& r, int encoding)
385{
386 sock->inStream().stopTiming();
387}
388
389void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p)
390{
391 desktop->fillRect(r,p);
392}
393void CConn::imageRect(const rfb::Rect& r, void* p)
394{
395 desktop->imageRect(r,p);
396}
397void CConn::copyRect(const rfb::Rect& r, int sx, int sy)
398{
399 desktop->copyRect(r,sx,sy);
400}
401void CConn::setCursor(int width, int height, const Point& hotspot,
402 void* data, void* mask)
403{
Pierre Ossman835b4ef2011-06-08 17:02:36 +0000404 desktop->setCursor(width, height, hotspot, data, mask);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000405}
406
407////////////////////// Internal methods //////////////////////
408
409void CConn::resizeFramebuffer()
410{
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000411 if (!desktop)
412 return;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000413
Pierre Ossman6455d852011-06-01 09:33:00 +0000414 desktop->resizeFramebuffer(cp.width, cp.height);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000415}
416
417// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
418// to the connection speed:
419//
420// First we wait for at least one second of bandwidth measurement.
421//
422// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
423// which should be perceptually lossless.
424//
425// If the bandwidth is below that, we choose a more lossy JPEG quality.
426//
427// If the bandwidth drops below 256 Kbps, we switch to palette mode.
428//
429// Note: The system here is fairly arbitrary and should be replaced
430// with something more intelligent at the server end.
431//
432void CConn::autoSelectFormatAndEncoding()
433{
434 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
435 unsigned int timeWaited = sock->inStream().timeWaited();
436 bool newFullColour = fullColour;
437 int newQualityLevel = qualityLevel;
438
439 // Always use Tight
440 if (currentEncoding != encodingTight) {
441 currentEncoding = encodingTight;
442 encodingChange = true;
443 }
444
445 // Check that we have a decent bandwidth measurement
446 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
447 return;
448
449 // Select appropriate quality level
450 if (!noJpeg) {
451 if (kbitsPerSecond > 16000)
452 newQualityLevel = 8;
453 else
454 newQualityLevel = 6;
455
456 if (newQualityLevel != qualityLevel) {
457 vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
458 kbitsPerSecond, newQualityLevel);
459 cp.qualityLevel = newQualityLevel;
460 qualityLevel.setParam(newQualityLevel);
461 encodingChange = true;
462 }
463 }
464
465 if (cp.beforeVersion(3, 8)) {
466 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
467 // cursors "asynchronously". If this happens in the middle of a
468 // pixel format change, the server will encode the cursor with
469 // the old format, but the client will try to decode it
470 // according to the new format. This will lead to a
471 // crash. Therefore, we do not allow automatic format change for
472 // old servers.
473 return;
474 }
475
476 // Select best color level
477 newFullColour = (kbitsPerSecond > 256);
478 if (newFullColour != fullColour) {
479 vlog.info(_("Throughput %d kbit/s - full color is now %s"),
480 kbitsPerSecond,
481 newFullColour ? _("enabled") : _("disabled"));
482 fullColour.setParam(newFullColour);
483 formatChange = true;
484 }
485}
486
487// checkEncodings() sends a setEncodings message if one is needed.
488void CConn::checkEncodings()
489{
490 if (encodingChange && writer()) {
491 vlog.info(_("Using %s encoding"),encodingName(currentEncoding));
492 writer()->writeSetEncodings(currentEncoding, true);
493 encodingChange = false;
494 }
495}
496
497// requestNewUpdate() requests an update from the server, having set the
498// format and encoding appropriately.
499void CConn::requestNewUpdate()
500{
501 if (formatChange) {
502 PixelFormat pf;
503
504 /* Catch incorrect requestNewUpdate calls */
505 assert(pendingUpdate == false);
506
507 if (fullColour) {
508 pf = fullColourPF;
509 } else {
510 if (lowColourLevel == 0)
Pierre Ossmancf836f22011-07-14 14:34:09 +0000511 pf = verylowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000512 else if (lowColourLevel == 1)
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000513 pf = lowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000514 else
Pierre Ossmancf836f22011-07-14 14:34:09 +0000515 pf = mediumColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000516 }
517 char str[256];
518 pf.print(str, 256);
519 vlog.info(_("Using pixel format %s"),str);
520 desktop->setServerPF(pf);
521 cp.setPF(pf);
522 writer()->writeSetPixelFormat(pf);
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000523
524 forceNonincremental = true;
525
526 formatChange = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000527 }
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000528
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000529 checkEncodings();
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000530
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000531 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000532 !forceNonincremental);
533
534 forceNonincremental = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000535}
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000536
537void CConn::handleOptions(void *data)
538{
539 CConn *self = (CConn*)data;
540
541 // Checking all the details of the current set of encodings is just
542 // a pain. Assume something has changed, as resending the encoding
543 // list is cheap. Avoid overriding what the auto logic has selected
544 // though.
545 if (!autoSelect) {
546 int encNum = encodingNum(preferredEncoding);
547
548 if (encNum != -1)
549 self->currentEncoding = encNum;
550
551 self->cp.qualityLevel = qualityLevel;
552 }
553
Pierre Ossmanda389562011-06-09 08:24:37 +0000554 self->cp.supportsLocalCursor = true;
555
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000556 self->cp.customCompressLevel = customCompressLevel;
557 self->cp.compressLevel = compressLevel;
558
559 self->cp.noJpeg = noJpeg;
560
561 self->encodingChange = true;
562
563 // Format changes refreshes the entire screen though and are therefore
564 // very costly. It's probably worth the effort to see if it is necessary
565 // here.
566 PixelFormat pf;
567
568 if (fullColour) {
569 pf = self->fullColourPF;
570 } else {
571 if (lowColourLevel == 0)
Pierre Ossmancf836f22011-07-14 14:34:09 +0000572 pf = verylowColourPF;
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000573 else if (lowColourLevel == 1)
574 pf = lowColourPF;
575 else
Pierre Ossmancf836f22011-07-14 14:34:09 +0000576 pf = mediumColourPF;
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000577 }
578
579 if (!pf.equal(self->cp.pf()))
580 self->formatChange = true;
581}