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