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