blob: 45189d738e01408aadf98f3aa807c859e96e7140 [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>
21#include <unistd.h>
22
23#include <rfb/CMsgWriter.h>
24#include <rfb/encodings.h>
25#include <rfb/Hostname.h>
26#include <rfb/LogWriter.h>
27#include <rfb/util.h>
28#include <rfb/screenTypes.h>
29#include <rfb/Timer.h>
30#include <network/TcpSocket.h>
31
32#include <FL/Fl.H>
33#include <FL/fl_ask.H>
34
35#include "CConn.h"
36#include "i18n.h"
37#include "parameters.h"
38
39using namespace rdr;
40using namespace rfb;
41using namespace std;
42
43extern void exit_vncviewer();
44
45static rfb::LogWriter vlog("CConn");
46
47CConn::CConn(const char* vncServerName)
48 : serverHost(0), serverPort(0), sock(NULL), desktop(NULL),
49 currentEncoding(encodingTight), lastServerEncoding((unsigned int)-1),
50 formatChange(false), encodingChange(false),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +000051 firstUpdate(true), pendingUpdate(false),
52 forceNonincremental(false)
Pierre Ossman5156d5e2011-03-09 09:42:34 +000053{
54 setShared(::shared);
55
56 int encNum = encodingNum(preferredEncoding);
57 if (encNum != -1)
58 currentEncoding = encNum;
59
60 cp.supportsDesktopResize = true;
61 cp.supportsExtendedDesktopSize = true;
62 cp.supportsDesktopRename = true;
63 cp.supportsLocalCursor = useLocalCursor;
64
65 cp.customCompressLevel = customCompressLevel;
66 cp.compressLevel = compressLevel;
67
68 cp.noJpeg = noJpeg;
69 cp.qualityLevel = qualityLevel;
70
71 try {
72 getHostAndPort(vncServerName, &serverHost, &serverPort);
73
74 sock = new network::TcpSocket(serverHost, serverPort);
75 vlog.info(_("connected to host %s port %d"), serverHost, serverPort);
76 } catch (rdr::Exception& e) {
77 vlog.error(e.str());
78 fl_alert(e.str());
79 exit_vncviewer();
80 return;
81 }
82
83 Fl::add_fd(sock->getFd(), FL_READ | FL_EXCEPT, socketEvent, this);
84
85 // See callback below
86 sock->inStream().setBlockCallback(this);
87
88 setServerName(serverHost);
89 setStreams(&sock->inStream(), &sock->outStream());
90
91 initialiseProtocol();
92}
93
94CConn::~CConn()
95{
96 free(serverHost);
97 if (sock)
98 Fl::remove_fd(sock->getFd());
99 delete sock;
100}
101
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000102void CConn::refreshFramebuffer()
103{
104 // FIXME: We cannot safely trigger an update request directly but must
105 // wait for the next update to arrive.
106 if (!formatChange)
107 forceNonincremental = true;
108}
109
Pierre Ossman2eb1d112011-05-16 12:18:08 +0000110const char *CConn::connectionInfo()
111{
112 static char infoText[1024] = "";
113
114 char pfStr[100];
115 char spfStr[100];
116
117 cp.pf().print(pfStr, 100);
118 serverPF.print(spfStr, 100);
119
120 int secType = csecurity->getType();
121
122 snprintf(infoText, sizeof(infoText),
123 _("Desktop name: %.80s\n"
124 "Host: %.80s port: %d\n"
125 "Size: %d x %d\n"
126 "Pixel format: %s\n"
127 "(server default %s)\n"
128 "Requested encoding: %s\n"
129 "Last used encoding: %s\n"
130 "Line speed estimate: %d kbit/s\n"
131 "Protocol version: %d.%d\n"
132 "Security method: %s\n"),
133 cp.name(), serverHost, serverPort, cp.width, cp.height,
134 pfStr, spfStr, encodingName(currentEncoding),
135 encodingName(lastServerEncoding),
136 sock->inStream().kbitsPerSecond(),
137 cp.majorVersion, cp.minorVersion,
138 secTypeName(secType));
139
140 return infoText;
141}
142
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000143// The RFB core is not properly asynchronous, so it calls this callback
144// whenever it needs to block to wait for more data. Since FLTK is
145// monitoring the socket, we just make sure FLTK gets to run.
146
147void CConn::blockCallback()
148{
149 int next_timer;
150
151 next_timer = Timer::checkTimeouts();
152 if (next_timer == 0)
153 next_timer = INT_MAX;
154
155 Fl::wait((double)next_timer / 1000.0);
156}
157
158void CConn::socketEvent(int fd, void *data)
159{
160 CConn *cc;
161 static bool recursing = false;
162
163 assert(data);
164 cc = (CConn*)data;
165
166 // I don't think processMsg() is recursion safe, so add this check
167 if (recursing)
168 return;
169
170 recursing = true;
171
172 try {
173 // processMsg() only processes one message, so we need to loop
174 // until the buffers are empty or things will stall.
175 do {
176 cc->processMsg();
177 } while (cc->sock->inStream().checkNoWait(1));
178 } catch (rdr::EndOfStream& e) {
179 vlog.info(e.str());
180 exit_vncviewer();
181 } catch (rdr::Exception& e) {
182 vlog.error(e.str());
183 fl_alert(e.str());
184 exit_vncviewer();
185 }
186
187 recursing = false;
188}
189
190////////////////////// CConnection callback methods //////////////////////
191
192// serverInit() is called when the serverInit message has been received. At
193// this point we create the desktop window and display it. We also tell the
194// server the pixel format and encodings to use and request the first update.
195void CConn::serverInit()
196{
197 CConnection::serverInit();
198
199 // If using AutoSelect with old servers, start in FullColor
200 // mode. See comment in autoSelectFormatAndEncoding.
201 if (cp.beforeVersion(3, 8) && autoSelect)
202 fullColour.setParam(true);
203
204 serverPF = cp.pf();
205
206 desktop = new DesktopWindow(cp.width, cp.height, cp.name(), serverPF, this);
207 fullColourPF = desktop->getPreferredPF();
208
209 formatChange = encodingChange = true;
210 requestNewUpdate();
211}
212
213// setDesktopSize() is called when the desktop size changes (including when
214// it is set initially).
215void CConn::setDesktopSize(int w, int h)
216{
217 CConnection::setDesktopSize(w,h);
218 resizeFramebuffer();
219}
220
221// setExtendedDesktopSize() is a more advanced version of setDesktopSize()
222void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
223 const rfb::ScreenSet& layout)
224{
225 CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
226
227 if ((reason == reasonClient) && (result != resultSuccess)) {
228 vlog.error(_("SetDesktopSize failed: %d"), result);
229 return;
230 }
231
232 resizeFramebuffer();
233}
234
235// setName() is called when the desktop name changes
236void CConn::setName(const char* name)
237{
238 CConnection::setName(name);
239 if (desktop)
240 desktop->setName(name);
241}
242
243// framebufferUpdateStart() is called at the beginning of an update.
244// Here we try to send out a new framebuffer update request so that the
245// next update can be sent out in parallel with us decoding the current
246// one. We cannot do this if we're in the middle of a format change
247// though.
248void CConn::framebufferUpdateStart()
249{
250 if (!formatChange) {
251 pendingUpdate = true;
252 requestNewUpdate();
253 } else
254 pendingUpdate = false;
255}
256
257// framebufferUpdateEnd() is called at the end of an update.
258// For each rectangle, the FdInStream will have timed the speed
259// of the connection, allowing us to select format and encoding
260// appropriately, and then request another incremental update.
261void CConn::framebufferUpdateEnd()
262{
263 desktop->updateWindow();
264
265 if (firstUpdate) {
266 int width, height;
267
268 if (cp.supportsSetDesktopSize &&
269 sscanf(desktopSize.getValueStr(), "%dx%d", &width, &height) == 2) {
270 ScreenSet layout;
271
272 layout = cp.screenLayout;
273
274 if (layout.num_screens() == 0)
275 layout.add_screen(rfb::Screen());
276 else if (layout.num_screens() != 1) {
277 ScreenSet::iterator iter;
278
279 while (true) {
280 iter = layout.begin();
281 ++iter;
282
283 if (iter == layout.end())
284 break;
285
286 layout.remove_screen(iter->id);
287 }
288 }
289
290 layout.begin()->dimensions.tl.x = 0;
291 layout.begin()->dimensions.tl.y = 0;
292 layout.begin()->dimensions.br.x = width;
293 layout.begin()->dimensions.br.y = height;
294
295 writer()->writeSetDesktopSize(width, height, layout);
296 }
297
298 firstUpdate = false;
299 }
300
301 // A format change prevented us from sending this before the update,
302 // so make sure to send it now.
303 if (formatChange && !pendingUpdate)
304 requestNewUpdate();
305
306 // Compute new settings based on updated bandwidth values
307 if (autoSelect)
308 autoSelectFormatAndEncoding();
309
310 // Make sure that the FLTK handling and the timers gets some CPU time
311 // in case of back to back framebuffer updates.
312 Fl::check();
313 Timer::checkTimeouts();
314}
315
316// The rest of the callbacks are fairly self-explanatory...
317
318void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
319{
320 desktop->setColourMapEntries(firstColour, nColours, rgbs);
321}
322
323void CConn::bell()
324{
325 fl_beep();
326}
327
328void CConn::serverCutText(const char* str, rdr::U32 len)
329{
330// desktop->serverCutText(str,len);
331}
332
333// We start timing on beginRect and stop timing on endRect, to
334// avoid skewing the bandwidth estimation as a result of the server
335// being slow or the network having high latency
336void CConn::beginRect(const Rect& r, int encoding)
337{
338 sock->inStream().startTiming();
339 if (encoding != encodingCopyRect) {
340 lastServerEncoding = encoding;
341 }
342}
343
344void CConn::endRect(const Rect& r, int encoding)
345{
346 sock->inStream().stopTiming();
347}
348
349void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p)
350{
351 desktop->fillRect(r,p);
352}
353void CConn::imageRect(const rfb::Rect& r, void* p)
354{
355 desktop->imageRect(r,p);
356}
357void CConn::copyRect(const rfb::Rect& r, int sx, int sy)
358{
359 desktop->copyRect(r,sx,sy);
360}
361void CConn::setCursor(int width, int height, const Point& hotspot,
362 void* data, void* mask)
363{
364// desktop->setCursor(width, height, hotspot, data, mask);
365}
366
367////////////////////// Internal methods //////////////////////
368
369void CConn::resizeFramebuffer()
370{
371/*
372 if (!desktop)
373 return;
374 if ((desktop->width() == cp.width) && (desktop->height() == cp.height))
375 return;
376
377 desktop->resize(cp.width, cp.height);
378*/
379}
380
381// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
382// to the connection speed:
383//
384// First we wait for at least one second of bandwidth measurement.
385//
386// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
387// which should be perceptually lossless.
388//
389// If the bandwidth is below that, we choose a more lossy JPEG quality.
390//
391// If the bandwidth drops below 256 Kbps, we switch to palette mode.
392//
393// Note: The system here is fairly arbitrary and should be replaced
394// with something more intelligent at the server end.
395//
396void CConn::autoSelectFormatAndEncoding()
397{
398 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
399 unsigned int timeWaited = sock->inStream().timeWaited();
400 bool newFullColour = fullColour;
401 int newQualityLevel = qualityLevel;
402
403 // Always use Tight
404 if (currentEncoding != encodingTight) {
405 currentEncoding = encodingTight;
406 encodingChange = true;
407 }
408
409 // Check that we have a decent bandwidth measurement
410 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
411 return;
412
413 // Select appropriate quality level
414 if (!noJpeg) {
415 if (kbitsPerSecond > 16000)
416 newQualityLevel = 8;
417 else
418 newQualityLevel = 6;
419
420 if (newQualityLevel != qualityLevel) {
421 vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
422 kbitsPerSecond, newQualityLevel);
423 cp.qualityLevel = newQualityLevel;
424 qualityLevel.setParam(newQualityLevel);
425 encodingChange = true;
426 }
427 }
428
429 if (cp.beforeVersion(3, 8)) {
430 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
431 // cursors "asynchronously". If this happens in the middle of a
432 // pixel format change, the server will encode the cursor with
433 // the old format, but the client will try to decode it
434 // according to the new format. This will lead to a
435 // crash. Therefore, we do not allow automatic format change for
436 // old servers.
437 return;
438 }
439
440 // Select best color level
441 newFullColour = (kbitsPerSecond > 256);
442 if (newFullColour != fullColour) {
443 vlog.info(_("Throughput %d kbit/s - full color is now %s"),
444 kbitsPerSecond,
445 newFullColour ? _("enabled") : _("disabled"));
446 fullColour.setParam(newFullColour);
447 formatChange = true;
448 }
449}
450
451// checkEncodings() sends a setEncodings message if one is needed.
452void CConn::checkEncodings()
453{
454 if (encodingChange && writer()) {
455 vlog.info(_("Using %s encoding"),encodingName(currentEncoding));
456 writer()->writeSetEncodings(currentEncoding, true);
457 encodingChange = false;
458 }
459}
460
461// requestNewUpdate() requests an update from the server, having set the
462// format and encoding appropriately.
463void CConn::requestNewUpdate()
464{
465 if (formatChange) {
466 PixelFormat pf;
467
468 /* Catch incorrect requestNewUpdate calls */
469 assert(pendingUpdate == false);
470
471 if (fullColour) {
472 pf = fullColourPF;
473 } else {
474 if (lowColourLevel == 0)
475 pf = PixelFormat(8,3,0,1,1,1,1,2,1,0);
476 else if (lowColourLevel == 1)
477 pf = PixelFormat(8,6,0,1,3,3,3,4,2,0);
478 else
479 pf = PixelFormat(8,8,0,0);
480 }
481 char str[256];
482 pf.print(str, 256);
483 vlog.info(_("Using pixel format %s"),str);
484 desktop->setServerPF(pf);
485 cp.setPF(pf);
486 writer()->writeSetPixelFormat(pf);
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000487
488 forceNonincremental = true;
489
490 formatChange = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000491 }
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000492
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000493 checkEncodings();
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000494
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000495 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000496 !forceNonincremental);
497
498 forceNonincremental = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000499}