blob: 9edb80d30837fb8ffae4f49bdf95d86001068d60 [file] [log] [blame]
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +00001/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved.
2 *
3 * This is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This software is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
16 * USA.
17 */
18//
19// All-new VNC viewer for X.
20//
21
22#include <string.h>
23#include <stdio.h>
24#include <ctype.h>
25#include <stdlib.h>
26#include <sys/time.h>
27#include <sys/types.h>
28#include <sys/stat.h>
29#include <sys/wait.h>
30#include <unistd.h>
31#include <errno.h>
32#include <signal.h>
Adam Tkac04b7fd22008-03-19 16:14:48 +000033#include <locale.h>
Adam Tkac21779fd2010-10-29 12:17:19 +000034#include <os/os.h>
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000035#include <rfb/Logger_stdio.h>
36#include <rfb/LogWriter.h>
37#include <network/TcpSocket.h>
38#include "TXWindow.h"
39#include "TXMsgBox.h"
40#include "CConn.h"
41
Adam Tkac0c65d8a2008-04-17 16:37:08 +000042#include "gettext.h"
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000043#define _(String) gettext (String)
44#define gettext_noop(String) String
45#define N_(String) gettext_noop (String)
46
47rfb::LogWriter vlog("main");
48
49using namespace network;
50using namespace rfb;
51using namespace std;
52
53IntParameter pointerEventInterval("PointerEventInterval",
54 "Time in milliseconds to rate-limit"
55 " successive pointer events", 0);
56IntParameter wmDecorationWidth("WMDecorationWidth", "Width of window manager "
57 "decoration around a window", 6);
58IntParameter wmDecorationHeight("WMDecorationHeight", "Height of window "
59 "manager decoration around a window", 24);
60StringParameter passwordFile("PasswordFile",
61 "Password file for VNC authentication", "");
Adam Tkac1d15e2d2010-04-23 14:06:38 +000062AliasParameter passwd("passwd", "Alias for PasswordFile", &passwordFile);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000063
64BoolParameter useLocalCursor("UseLocalCursor",
65 "Render the mouse cursor locally", true);
66BoolParameter dotWhenNoCursor("DotWhenNoCursor",
67 "Show the dot cursor when the server sends an "
68 "invisible cursor", true);
69BoolParameter autoSelect("AutoSelect",
70 "Auto select pixel format and encoding. "
71 "Default if PreferredEncoding and FullColor are not specified.",
72 true);
73BoolParameter fullColour("FullColor",
74 "Use full color", true);
75AliasParameter fullColourAlias("FullColour", "Alias for FullColor", &fullColour);
76IntParameter lowColourLevel("LowColorLevel",
77 "Color level to use on slow connections. "
78 "0 = Very Low (8 colors), 1 = Low (64 colors), "
79 "2 = Medium (256 colors)", 2);
80AliasParameter lowColourLevelAlias("LowColourLevel", "Alias for LowColorLevel", &lowColourLevel);
81StringParameter preferredEncoding("PreferredEncoding",
82 "Preferred encoding to use (Tight, ZRLE, Hextile or"
83 " Raw)", "Tight");
84BoolParameter fullScreen("FullScreen", "Full screen mode", false);
85BoolParameter viewOnly("ViewOnly",
86 "Don't send any mouse or keyboard events to the server",
87 false);
88BoolParameter shared("Shared",
89 "Don't disconnect other viewers upon connection - "
90 "share the desktop instead",
91 false);
92BoolParameter acceptClipboard("AcceptClipboard",
93 "Accept clipboard changes from the server",
94 true);
95BoolParameter sendClipboard("SendClipboard",
96 "Send clipboard changes to the server", true);
97BoolParameter sendPrimary("SendPrimary",
98 "Send the primary selection and cut buffer to the "
99 "server as well as the clipboard selection",
100 true);
101
Pierre Ossmaneb3cecb2009-03-23 16:49:47 +0000102StringParameter desktopSize("DesktopSize",
103 "Reconfigure desktop size on the server on "
104 "connect (if possible)", "");
105
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000106BoolParameter listenMode("listen", "Listen for connections from VNC servers",
107 false);
108StringParameter geometry("geometry", "X geometry specification", "");
109StringParameter displayname("display", "The X display", "");
110
111StringParameter via("via", "Gateway to tunnel via", "");
112
113BoolParameter customCompressLevel("CustomCompressLevel",
114 "Use custom compression level. "
115 "Default if CompressLevel is specified.", false);
116
117IntParameter compressLevel("CompressLevel",
118 "Use specified compression level"
119 "0 = Low, 9 = High",
120 6);
121
122BoolParameter noJpeg("NoJPEG",
123 "Disable lossy JPEG compression in Tight encoding.",
124 false);
125
126IntParameter qualityLevel("QualityLevel",
127 "JPEG quality level. "
128 "0 = Low, 9 = High",
Pierre Ossman7dfa22e2009-03-12 13:03:22 +0000129 8);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000130
131char aboutText[1024];
132char* programName;
133extern char buildtime[];
134
135static void CleanupSignalHandler(int sig)
136{
137 // CleanupSignalHandler allows C++ object cleanup to happen because it calls
138 // exit() rather than the default which is to abort.
139 vlog.info("CleanupSignalHandler called");
140 exit(1);
141}
142
143// XLoginIconifier is a class which iconifies the XDM login window when it has
144// grabbed the keyboard, thus releasing the grab, allowing the viewer to use
145// the keyboard. It remaps the xlogin window on exit.
146class XLoginIconifier {
147public:
148 Display* dpy;
149 Window xlogin;
150 XLoginIconifier() : dpy(0), xlogin(0) {}
151 void iconify(Display* dpy_) {
152 dpy = dpy_;
153 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), False, GrabModeSync,
154 GrabModeSync, CurrentTime) == GrabSuccess) {
155 XUngrabKeyboard(dpy, CurrentTime);
156 } else {
157 xlogin = TXWindow::windowWithName(dpy, DefaultRootWindow(dpy), "xlogin");
158 if (xlogin) {
159 XIconifyWindow(dpy, xlogin, DefaultScreen(dpy));
160 XSync(dpy, False);
161 }
162 }
163 }
164 ~XLoginIconifier() {
165 if (xlogin) {
166 fprintf(stderr,"~XLoginIconifier remapping xlogin\n");
167 XMapWindow(dpy, xlogin);
168 XFlush(dpy);
169 sleep(1);
170 }
171 }
172};
173
174static XLoginIconifier xloginIconifier;
175
176static void usage()
177{
178 fprintf(stderr,
179 "\nusage: %s [parameters] [host:displayNum] [parameters]\n"
180 " %s [parameters] -listen [port] [parameters]\n",
181 programName,programName);
182 fprintf(stderr,"\n"
183 "Parameters can be turned on with -<param> or off with -<param>=0\n"
184 "Parameters which take a value can be specified as "
185 "-<param> <value>\n"
186 "Other valid forms are <param>=<value> -<param>=<value> "
187 "--<param>=<value>\n"
188 "Parameter names are case-insensitive. The parameters are:\n\n");
189 Configuration::listParams(79, 14);
190 exit(1);
191}
192
193/* Tunnelling support. */
194static void
195interpretViaParam (char **gatewayHost, char **remoteHost,
196 int *remotePort, char **vncServerName,
197 int localPort)
198{
199 const int SERVER_PORT_OFFSET = 5900;
200 char *pos = strchr (*vncServerName, ':');
201 if (pos == NULL)
202 *remotePort = SERVER_PORT_OFFSET;
203 else {
204 int portOffset = SERVER_PORT_OFFSET;
205 size_t len;
206 *pos++ = '\0';
207 len = strlen (pos);
208 if (*pos == ':') {
209 /* Two colons is an absolute port number, not an offset. */
210 pos++;
211 len--;
212 portOffset = 0;
213 }
214 if (!len || strspn (pos, "-0123456789") != len )
215 usage ();
216 *remotePort = atoi (pos) + portOffset;
217 }
218
219 if (**vncServerName != '\0')
220 *remoteHost = *vncServerName;
221
Adam Tkacd36b6262009-09-04 10:57:20 +0000222 *gatewayHost = strDup (via.getValueStr ());
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000223 *vncServerName = new char[50];
224 sprintf (*vncServerName, "localhost::%d", localPort);
225}
226
227#ifndef HAVE_SETENV
228int
229setenv(const char *envname, const char * envval, int overwrite)
230{
231 if (envname && envval) {
232 char * envp = NULL;
233 envp = (char*)malloc(strlen(envname) + strlen(envval) + 2);
234 if (envp) {
235 // The putenv API guarantees memory leaks when
236 // changing environment variables repeatedly.
237 sprintf(envp, "%s=%s", envname, envval);
238
239 // Cannot free envp
240 putenv(envp);
241 return(0);
242 }
243 }
244 return(-1);
245}
246#endif
247
248static void
249createTunnel (const char *gatewayHost, const char *remoteHost,
250 int remotePort, int localPort)
251{
252 char *cmd = getenv ("VNC_VIA_CMD");
253 char *percent;
254 char lport[10], rport[10];
255 sprintf (lport, "%d", localPort);
256 sprintf (rport, "%d", remotePort);
257 setenv ("G", gatewayHost, 1);
258 setenv ("H", remoteHost, 1);
259 setenv ("R", rport, 1);
260 setenv ("L", lport, 1);
261 if (!cmd)
262 cmd = "/usr/bin/ssh -f -L \"$L\":\"$H\":\"$R\" \"$G\" sleep 20";
Peter Åstrand4eacc022009-02-27 10:12:14 +0000263 /* Compatibility with TigerVNC's method. */
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000264 while ((percent = strchr (cmd, '%')) != NULL)
265 *percent = '$';
266 system (cmd);
267}
268
269int main(int argc, char** argv)
270{
271 setlocale(LC_ALL, "");
Adam Tkac932e09b2008-04-17 15:45:58 +0000272 bindtextdomain(PACKAGE_NAME, LOCALEDIR);
273 textdomain(PACKAGE_NAME);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000274
Peter Åstrand4eacc022009-02-27 10:12:14 +0000275 const char englishAbout[] = N_("TigerVNC Viewer for X version %s - built %s\n"
Peter Åstrand3336ac42009-01-26 13:35:31 +0000276 "Copyright (C) 2002-2005 RealVNC Ltd.\n"
277 "Copyright (C) 2000-2006 TightVNC Group\n"
Peter Åstranda87caa62009-02-25 15:01:07 +0000278 "Copyright (C) 2004-2009 Peter Astrand for Cendio AB\n"
Peter Åstrand4eacc022009-02-27 10:12:14 +0000279 "See http://www.tigervnc.org for information on TigerVNC.");
Peter Åstrand3336ac42009-01-26 13:35:31 +0000280
281 // Write about text to console, still using normal locale codeset
282 snprintf(aboutText, sizeof(aboutText),
283 gettext(englishAbout), PACKAGE_VERSION, buildtime);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000284 fprintf(stderr,"\n%s\n", aboutText);
285
Peter Åstrand3336ac42009-01-26 13:35:31 +0000286 // Set gettext codeset to what our GUI toolkit uses. Since we are
287 // passing strings from strerror/gai_strerror to the GUI, these must
288 // be in GUI codeset as well.
Adam Tkac932e09b2008-04-17 15:45:58 +0000289 bind_textdomain_codeset(PACKAGE_NAME, "iso-8859-1");
Peter Åstrandaa409f12009-01-26 13:17:27 +0000290 bind_textdomain_codeset("libc", "iso-8859-1");
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000291
Peter Åstrand3336ac42009-01-26 13:35:31 +0000292 // Re-create the aboutText for the GUI, now using GUI codeset
293 snprintf(aboutText, sizeof(aboutText),
294 gettext(englishAbout), PACKAGE_VERSION, buildtime);
295
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000296 rfb::initStdIOLoggers();
297 rfb::LogWriter::setLogParams("*:stderr:30");
298
299 signal(SIGHUP, CleanupSignalHandler);
300 signal(SIGINT, CleanupSignalHandler);
301 signal(SIGTERM, CleanupSignalHandler);
302
303 programName = argv[0];
304 char* vncServerName = 0;
305 Display* dpy = 0;
306
Adam Tkacc58b3d12010-04-23 13:55:10 +0000307 Configuration::enableViewerParams();
308
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000309 for (int i = 1; i < argc; i++) {
310 if (Configuration::setParam(argv[i]))
311 continue;
312
313 if (argv[i][0] == '-') {
314 if (i+1 < argc) {
315 if (Configuration::setParam(&argv[i][1], argv[i+1])) {
316 i++;
317 continue;
318 }
319 }
320 usage();
321 }
322
323 vncServerName = argv[i];
324 }
325
326 // Create .vnc in the user's home directory if it doesn't already exist
Adam Tkac21779fd2010-10-29 12:17:19 +0000327 char* homeDir = NULL;
328 if (gethomedir(&homeDir) == -1)
329 vlog.error("Could not create .vnc directory: can't obtain home directory path.");
330 else {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000331 CharArray vncDir(strlen(homeDir)+6);
332 sprintf(vncDir.buf, "%s/.vnc", homeDir);
333 int result = mkdir(vncDir.buf, 0755);
334 if (result == -1 && errno != EEXIST)
335 vlog.error("Could not create .vnc directory: %s.", strerror(errno));
Adam Tkac21779fd2010-10-29 12:17:19 +0000336 delete [] homeDir;
337 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000338
339 if (!::autoSelect.hasBeenSet()) {
340 // Default to AutoSelect=0 if -PreferredEncoding or -FullColor is used
341 ::autoSelect.setParam(!::preferredEncoding.hasBeenSet()
342 && !::fullColour.hasBeenSet()
343 && !::fullColourAlias.hasBeenSet());
344 }
Adam Tkac21a5cc82009-10-07 15:14:33 +0000345 if (!::fullColour.hasBeenSet() && !::fullColourAlias.hasBeenSet()) {
346 // Default to FullColor=0 if AutoSelect=0 && LowColorLevel is set
347 if (!::autoSelect && (::lowColourLevel.hasBeenSet() ||
348 ::lowColourLevelAlias.hasBeenSet())) {
349 ::fullColour.setParam(false);
350 }
351 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000352 if (!::customCompressLevel.hasBeenSet()) {
353 // Default to CustomCompressLevel=1 if CompressLevel is used.
354 ::customCompressLevel.setParam(::compressLevel.hasBeenSet());
355 }
356
357 try {
358 /* Tunnelling support. */
359 if (strlen (via.getValueStr ()) > 0) {
360 char *gatewayHost = "";
361 char *remoteHost = "localhost";
362 int localPort = findFreeTcpPort ();
363 int remotePort;
364 if (!vncServerName)
365 usage();
366 interpretViaParam (&gatewayHost, &remoteHost, &remotePort,
367 &vncServerName, localPort);
368 createTunnel (gatewayHost, remoteHost, remotePort, localPort);
369 }
370
371 Socket* sock = 0;
372
373 if (listenMode) {
374 int port = 5500;
375 if (vncServerName && isdigit(vncServerName[0]))
376 port = atoi(vncServerName);
377
Adam Tkac93ff5db2010-02-05 15:54:10 +0000378 TcpListener listener(NULL, port);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000379
380 vlog.info("Listening on port %d\n",port);
381
382 while (true) {
383 sock = listener.accept();
384 int pid = fork();
385 if (pid < 0) { perror("fork"); exit(1); }
386 if (pid == 0) break; // child
387 delete sock;
388 int status;
389 while (wait3(&status, WNOHANG, 0) > 0) ;
390 }
391 }
392
393 CharArray displaynameStr(displayname.getData());
394 if (!(dpy = XOpenDisplay(TXWindow::strEmptyToNull(displaynameStr.buf)))) {
395 fprintf(stderr,"%s: unable to open display \"%s\"\n",
396 programName, XDisplayName(displaynameStr.buf));
397 exit(1);
398 }
399
400 TXWindow::init(dpy, "Vncviewer");
401 xloginIconifier.iconify(dpy);
402 CConn cc(dpy, argc, argv, sock, vncServerName, listenMode);
403
404 // X events are processed whenever reading from the socket would block.
405
406 while (true) {
407 cc.getInStream()->check(1);
408 cc.processMsg();
409 }
410
411 } catch (rdr::EndOfStream& e) {
412 vlog.info(e.str());
413 } catch (rdr::Exception& e) {
414 vlog.error(e.str());
415 if (dpy) {
416 TXMsgBox msgBox(dpy, e.str(), MB_OK, "VNC Viewer: Information");
417 msgBox.show();
418 }
419 return 1;
420 }
421
422 return 0;
423}