blob: e295c34425c19592affe85849c2b8a81f9a6e8dc [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());
Pierre Ossmane2ef5c12011-07-12 16:56:34 +0000201 exit_vncviewer(e.str());
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000202 }
203
204 recursing = false;
205}
206
207////////////////////// CConnection callback methods //////////////////////
208
209// serverInit() is called when the serverInit message has been received. At
210// this point we create the desktop window and display it. We also tell the
211// server the pixel format and encodings to use and request the first update.
212void CConn::serverInit()
213{
214 CConnection::serverInit();
215
216 // If using AutoSelect with old servers, start in FullColor
217 // mode. See comment in autoSelectFormatAndEncoding.
218 if (cp.beforeVersion(3, 8) && autoSelect)
219 fullColour.setParam(true);
220
221 serverPF = cp.pf();
222
223 desktop = new DesktopWindow(cp.width, cp.height, cp.name(), serverPF, this);
224 fullColourPF = desktop->getPreferredPF();
225
226 formatChange = encodingChange = true;
227 requestNewUpdate();
228}
229
230// setDesktopSize() is called when the desktop size changes (including when
231// it is set initially).
232void CConn::setDesktopSize(int w, int h)
233{
234 CConnection::setDesktopSize(w,h);
235 resizeFramebuffer();
236}
237
238// setExtendedDesktopSize() is a more advanced version of setDesktopSize()
239void CConn::setExtendedDesktopSize(int reason, int result, int w, int h,
240 const rfb::ScreenSet& layout)
241{
242 CConnection::setExtendedDesktopSize(reason, result, w, h, layout);
243
244 if ((reason == reasonClient) && (result != resultSuccess)) {
245 vlog.error(_("SetDesktopSize failed: %d"), result);
246 return;
247 }
248
249 resizeFramebuffer();
250}
251
252// setName() is called when the desktop name changes
253void CConn::setName(const char* name)
254{
255 CConnection::setName(name);
256 if (desktop)
257 desktop->setName(name);
258}
259
260// framebufferUpdateStart() is called at the beginning of an update.
261// Here we try to send out a new framebuffer update request so that the
262// next update can be sent out in parallel with us decoding the current
263// one. We cannot do this if we're in the middle of a format change
264// though.
265void CConn::framebufferUpdateStart()
266{
267 if (!formatChange) {
268 pendingUpdate = true;
269 requestNewUpdate();
270 } else
271 pendingUpdate = false;
272}
273
274// framebufferUpdateEnd() is called at the end of an update.
275// For each rectangle, the FdInStream will have timed the speed
276// of the connection, allowing us to select format and encoding
277// appropriately, and then request another incremental update.
278void CConn::framebufferUpdateEnd()
279{
280 desktop->updateWindow();
281
282 if (firstUpdate) {
283 int width, height;
284
285 if (cp.supportsSetDesktopSize &&
286 sscanf(desktopSize.getValueStr(), "%dx%d", &width, &height) == 2) {
287 ScreenSet layout;
288
289 layout = cp.screenLayout;
290
291 if (layout.num_screens() == 0)
292 layout.add_screen(rfb::Screen());
293 else if (layout.num_screens() != 1) {
294 ScreenSet::iterator iter;
295
296 while (true) {
297 iter = layout.begin();
298 ++iter;
299
300 if (iter == layout.end())
301 break;
302
303 layout.remove_screen(iter->id);
304 }
305 }
306
307 layout.begin()->dimensions.tl.x = 0;
308 layout.begin()->dimensions.tl.y = 0;
309 layout.begin()->dimensions.br.x = width;
310 layout.begin()->dimensions.br.y = height;
311
312 writer()->writeSetDesktopSize(width, height, layout);
313 }
314
315 firstUpdate = false;
316 }
317
318 // A format change prevented us from sending this before the update,
319 // so make sure to send it now.
320 if (formatChange && !pendingUpdate)
321 requestNewUpdate();
322
323 // Compute new settings based on updated bandwidth values
324 if (autoSelect)
325 autoSelectFormatAndEncoding();
326
327 // Make sure that the FLTK handling and the timers gets some CPU time
328 // in case of back to back framebuffer updates.
329 Fl::check();
330 Timer::checkTimeouts();
331}
332
333// The rest of the callbacks are fairly self-explanatory...
334
335void CConn::setColourMapEntries(int firstColour, int nColours, rdr::U16* rgbs)
336{
337 desktop->setColourMapEntries(firstColour, nColours, rgbs);
338}
339
340void CConn::bell()
341{
342 fl_beep();
343}
344
345void CConn::serverCutText(const char* str, rdr::U32 len)
346{
Pierre Ossman689c4582011-05-26 15:39:41 +0000347 char *buffer;
348 int size, ret;
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000349
Pierre Ossman689c4582011-05-26 15:39:41 +0000350 size = fl_utf8froma(NULL, 0, str, len);
351 if (size <= 0)
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000352 return;
Pierre Ossman689c4582011-05-26 15:39:41 +0000353
354 size++;
355
356 buffer = new char[size];
357
358 ret = fl_utf8froma(buffer, size, str, len);
359 assert(ret < size);
Pierre Ossmand81e8f42011-05-19 14:47:15 +0000360
361 vlog.debug("Got clipboard data: '%s'", buffer);
362
363 Fl::copy(buffer, ret, 1);
Pierre Ossman689c4582011-05-26 15:39:41 +0000364
365 delete [] buffer;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000366}
367
368// We start timing on beginRect and stop timing on endRect, to
369// avoid skewing the bandwidth estimation as a result of the server
370// being slow or the network having high latency
371void CConn::beginRect(const Rect& r, int encoding)
372{
373 sock->inStream().startTiming();
374 if (encoding != encodingCopyRect) {
375 lastServerEncoding = encoding;
376 }
377}
378
379void CConn::endRect(const Rect& r, int encoding)
380{
381 sock->inStream().stopTiming();
382}
383
384void CConn::fillRect(const rfb::Rect& r, rfb::Pixel p)
385{
386 desktop->fillRect(r,p);
387}
388void CConn::imageRect(const rfb::Rect& r, void* p)
389{
390 desktop->imageRect(r,p);
391}
392void CConn::copyRect(const rfb::Rect& r, int sx, int sy)
393{
394 desktop->copyRect(r,sx,sy);
395}
396void CConn::setCursor(int width, int height, const Point& hotspot,
397 void* data, void* mask)
398{
Pierre Ossman835b4ef2011-06-08 17:02:36 +0000399 desktop->setCursor(width, height, hotspot, data, mask);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000400}
401
402////////////////////// Internal methods //////////////////////
403
404void CConn::resizeFramebuffer()
405{
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000406 if (!desktop)
407 return;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000408
Pierre Ossman6455d852011-06-01 09:33:00 +0000409 desktop->resizeFramebuffer(cp.width, cp.height);
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000410}
411
412// autoSelectFormatAndEncoding() chooses the format and encoding appropriate
413// to the connection speed:
414//
415// First we wait for at least one second of bandwidth measurement.
416//
417// Above 16Mbps (i.e. LAN), we choose the second highest JPEG quality,
418// which should be perceptually lossless.
419//
420// If the bandwidth is below that, we choose a more lossy JPEG quality.
421//
422// If the bandwidth drops below 256 Kbps, we switch to palette mode.
423//
424// Note: The system here is fairly arbitrary and should be replaced
425// with something more intelligent at the server end.
426//
427void CConn::autoSelectFormatAndEncoding()
428{
429 int kbitsPerSecond = sock->inStream().kbitsPerSecond();
430 unsigned int timeWaited = sock->inStream().timeWaited();
431 bool newFullColour = fullColour;
432 int newQualityLevel = qualityLevel;
433
434 // Always use Tight
435 if (currentEncoding != encodingTight) {
436 currentEncoding = encodingTight;
437 encodingChange = true;
438 }
439
440 // Check that we have a decent bandwidth measurement
441 if ((kbitsPerSecond == 0) || (timeWaited < 10000))
442 return;
443
444 // Select appropriate quality level
445 if (!noJpeg) {
446 if (kbitsPerSecond > 16000)
447 newQualityLevel = 8;
448 else
449 newQualityLevel = 6;
450
451 if (newQualityLevel != qualityLevel) {
452 vlog.info(_("Throughput %d kbit/s - changing to quality %d"),
453 kbitsPerSecond, newQualityLevel);
454 cp.qualityLevel = newQualityLevel;
455 qualityLevel.setParam(newQualityLevel);
456 encodingChange = true;
457 }
458 }
459
460 if (cp.beforeVersion(3, 8)) {
461 // Xvnc from TightVNC 1.2.9 sends out FramebufferUpdates with
462 // cursors "asynchronously". If this happens in the middle of a
463 // pixel format change, the server will encode the cursor with
464 // the old format, but the client will try to decode it
465 // according to the new format. This will lead to a
466 // crash. Therefore, we do not allow automatic format change for
467 // old servers.
468 return;
469 }
470
471 // Select best color level
472 newFullColour = (kbitsPerSecond > 256);
473 if (newFullColour != fullColour) {
474 vlog.info(_("Throughput %d kbit/s - full color is now %s"),
475 kbitsPerSecond,
476 newFullColour ? _("enabled") : _("disabled"));
477 fullColour.setParam(newFullColour);
478 formatChange = true;
479 }
480}
481
482// checkEncodings() sends a setEncodings message if one is needed.
483void CConn::checkEncodings()
484{
485 if (encodingChange && writer()) {
486 vlog.info(_("Using %s encoding"),encodingName(currentEncoding));
487 writer()->writeSetEncodings(currentEncoding, true);
488 encodingChange = false;
489 }
490}
491
492// requestNewUpdate() requests an update from the server, having set the
493// format and encoding appropriately.
494void CConn::requestNewUpdate()
495{
496 if (formatChange) {
497 PixelFormat pf;
498
499 /* Catch incorrect requestNewUpdate calls */
500 assert(pendingUpdate == false);
501
502 if (fullColour) {
503 pf = fullColourPF;
504 } else {
505 if (lowColourLevel == 0)
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000506 pf = mediumColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000507 else if (lowColourLevel == 1)
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000508 pf = lowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000509 else
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000510 pf = verylowColourPF;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000511 }
512 char str[256];
513 pf.print(str, 256);
514 vlog.info(_("Using pixel format %s"),str);
515 desktop->setServerPF(pf);
516 cp.setPF(pf);
517 writer()->writeSetPixelFormat(pf);
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000518
519 forceNonincremental = true;
520
521 formatChange = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000522 }
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000523
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000524 checkEncodings();
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000525
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000526 writer()->writeFramebufferUpdateRequest(Rect(0, 0, cp.width, cp.height),
Pierre Ossmand4c61ce2011-04-29 11:18:12 +0000527 !forceNonincremental);
528
529 forceNonincremental = false;
Pierre Ossman5156d5e2011-03-09 09:42:34 +0000530}
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000531
532void CConn::handleOptions(void *data)
533{
534 CConn *self = (CConn*)data;
535
536 // Checking all the details of the current set of encodings is just
537 // a pain. Assume something has changed, as resending the encoding
538 // list is cheap. Avoid overriding what the auto logic has selected
539 // though.
540 if (!autoSelect) {
541 int encNum = encodingNum(preferredEncoding);
542
543 if (encNum != -1)
544 self->currentEncoding = encNum;
545
546 self->cp.qualityLevel = qualityLevel;
547 }
548
Pierre Ossmanda389562011-06-09 08:24:37 +0000549 self->cp.supportsLocalCursor = true;
550
Pierre Ossmanf4f30942011-05-17 09:39:07 +0000551 self->cp.customCompressLevel = customCompressLevel;
552 self->cp.compressLevel = compressLevel;
553
554 self->cp.noJpeg = noJpeg;
555
556 self->encodingChange = true;
557
558 // Format changes refreshes the entire screen though and are therefore
559 // very costly. It's probably worth the effort to see if it is necessary
560 // here.
561 PixelFormat pf;
562
563 if (fullColour) {
564 pf = self->fullColourPF;
565 } else {
566 if (lowColourLevel == 0)
567 pf = mediumColourPF;
568 else if (lowColourLevel == 1)
569 pf = lowColourPF;
570 else
571 pf = verylowColourPF;
572 }
573
574 if (!pf.equal(self->cp.pf()))
575 self->formatChange = true;
576}