blob: e419c78bd7f3a522983cedb2e286fcaded469ee1 [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>
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000034#include <rfb/Logger_stdio.h>
35#include <rfb/LogWriter.h>
36#include <network/TcpSocket.h>
37#include "TXWindow.h"
38#include "TXMsgBox.h"
39#include "CConn.h"
40
41#include <intl/gettext.h>
42#define _(String) gettext (String)
43#define gettext_noop(String) String
44#define N_(String) gettext_noop (String)
45
46rfb::LogWriter vlog("main");
47
48using namespace network;
49using namespace rfb;
50using namespace std;
51
52IntParameter pointerEventInterval("PointerEventInterval",
53 "Time in milliseconds to rate-limit"
54 " successive pointer events", 0);
55IntParameter wmDecorationWidth("WMDecorationWidth", "Width of window manager "
56 "decoration around a window", 6);
57IntParameter wmDecorationHeight("WMDecorationHeight", "Height of window "
58 "manager decoration around a window", 24);
59StringParameter passwordFile("PasswordFile",
60 "Password file for VNC authentication", "");
61AliasParameter rfbauth("passwd", "Alias for PasswordFile", &passwordFile);
62
63BoolParameter useLocalCursor("UseLocalCursor",
64 "Render the mouse cursor locally", true);
65BoolParameter dotWhenNoCursor("DotWhenNoCursor",
66 "Show the dot cursor when the server sends an "
67 "invisible cursor", true);
68BoolParameter autoSelect("AutoSelect",
69 "Auto select pixel format and encoding. "
70 "Default if PreferredEncoding and FullColor are not specified.",
71 true);
72BoolParameter fullColour("FullColor",
73 "Use full color", true);
74AliasParameter fullColourAlias("FullColour", "Alias for FullColor", &fullColour);
75IntParameter lowColourLevel("LowColorLevel",
76 "Color level to use on slow connections. "
77 "0 = Very Low (8 colors), 1 = Low (64 colors), "
78 "2 = Medium (256 colors)", 2);
79AliasParameter lowColourLevelAlias("LowColourLevel", "Alias for LowColorLevel", &lowColourLevel);
80StringParameter preferredEncoding("PreferredEncoding",
81 "Preferred encoding to use (Tight, ZRLE, Hextile or"
82 " Raw)", "Tight");
83BoolParameter fullScreen("FullScreen", "Full screen mode", false);
84BoolParameter viewOnly("ViewOnly",
85 "Don't send any mouse or keyboard events to the server",
86 false);
87BoolParameter shared("Shared",
88 "Don't disconnect other viewers upon connection - "
89 "share the desktop instead",
90 false);
91BoolParameter acceptClipboard("AcceptClipboard",
92 "Accept clipboard changes from the server",
93 true);
94BoolParameter sendClipboard("SendClipboard",
95 "Send clipboard changes to the server", true);
96BoolParameter sendPrimary("SendPrimary",
97 "Send the primary selection and cut buffer to the "
98 "server as well as the clipboard selection",
99 true);
100
101BoolParameter listenMode("listen", "Listen for connections from VNC servers",
102 false);
103StringParameter geometry("geometry", "X geometry specification", "");
104StringParameter displayname("display", "The X display", "");
105
106StringParameter via("via", "Gateway to tunnel via", "");
107
108BoolParameter customCompressLevel("CustomCompressLevel",
109 "Use custom compression level. "
110 "Default if CompressLevel is specified.", false);
111
112IntParameter compressLevel("CompressLevel",
113 "Use specified compression level"
114 "0 = Low, 9 = High",
115 6);
116
117BoolParameter noJpeg("NoJPEG",
118 "Disable lossy JPEG compression in Tight encoding.",
119 false);
120
121IntParameter qualityLevel("QualityLevel",
122 "JPEG quality level. "
123 "0 = Low, 9 = High",
124 6);
125
126char aboutText[1024];
127char* programName;
128extern char buildtime[];
129
130static void CleanupSignalHandler(int sig)
131{
132 // CleanupSignalHandler allows C++ object cleanup to happen because it calls
133 // exit() rather than the default which is to abort.
134 vlog.info("CleanupSignalHandler called");
135 exit(1);
136}
137
138// XLoginIconifier is a class which iconifies the XDM login window when it has
139// grabbed the keyboard, thus releasing the grab, allowing the viewer to use
140// the keyboard. It remaps the xlogin window on exit.
141class XLoginIconifier {
142public:
143 Display* dpy;
144 Window xlogin;
145 XLoginIconifier() : dpy(0), xlogin(0) {}
146 void iconify(Display* dpy_) {
147 dpy = dpy_;
148 if (XGrabKeyboard(dpy, DefaultRootWindow(dpy), False, GrabModeSync,
149 GrabModeSync, CurrentTime) == GrabSuccess) {
150 XUngrabKeyboard(dpy, CurrentTime);
151 } else {
152 xlogin = TXWindow::windowWithName(dpy, DefaultRootWindow(dpy), "xlogin");
153 if (xlogin) {
154 XIconifyWindow(dpy, xlogin, DefaultScreen(dpy));
155 XSync(dpy, False);
156 }
157 }
158 }
159 ~XLoginIconifier() {
160 if (xlogin) {
161 fprintf(stderr,"~XLoginIconifier remapping xlogin\n");
162 XMapWindow(dpy, xlogin);
163 XFlush(dpy);
164 sleep(1);
165 }
166 }
167};
168
169static XLoginIconifier xloginIconifier;
170
171static void usage()
172{
173 fprintf(stderr,
174 "\nusage: %s [parameters] [host:displayNum] [parameters]\n"
175 " %s [parameters] -listen [port] [parameters]\n",
176 programName,programName);
177 fprintf(stderr,"\n"
178 "Parameters can be turned on with -<param> or off with -<param>=0\n"
179 "Parameters which take a value can be specified as "
180 "-<param> <value>\n"
181 "Other valid forms are <param>=<value> -<param>=<value> "
182 "--<param>=<value>\n"
183 "Parameter names are case-insensitive. The parameters are:\n\n");
184 Configuration::listParams(79, 14);
185 exit(1);
186}
187
188/* Tunnelling support. */
189static void
190interpretViaParam (char **gatewayHost, char **remoteHost,
191 int *remotePort, char **vncServerName,
192 int localPort)
193{
194 const int SERVER_PORT_OFFSET = 5900;
195 char *pos = strchr (*vncServerName, ':');
196 if (pos == NULL)
197 *remotePort = SERVER_PORT_OFFSET;
198 else {
199 int portOffset = SERVER_PORT_OFFSET;
200 size_t len;
201 *pos++ = '\0';
202 len = strlen (pos);
203 if (*pos == ':') {
204 /* Two colons is an absolute port number, not an offset. */
205 pos++;
206 len--;
207 portOffset = 0;
208 }
209 if (!len || strspn (pos, "-0123456789") != len )
210 usage ();
211 *remotePort = atoi (pos) + portOffset;
212 }
213
214 if (**vncServerName != '\0')
215 *remoteHost = *vncServerName;
216
217 *gatewayHost = strDup (via.getValueStr ());
218 *vncServerName = new char[50];
219 sprintf (*vncServerName, "localhost::%d", localPort);
220}
221
222#ifndef HAVE_SETENV
223int
224setenv(const char *envname, const char * envval, int overwrite)
225{
226 if (envname && envval) {
227 char * envp = NULL;
228 envp = (char*)malloc(strlen(envname) + strlen(envval) + 2);
229 if (envp) {
230 // The putenv API guarantees memory leaks when
231 // changing environment variables repeatedly.
232 sprintf(envp, "%s=%s", envname, envval);
233
234 // Cannot free envp
235 putenv(envp);
236 return(0);
237 }
238 }
239 return(-1);
240}
241#endif
242
243static void
244createTunnel (const char *gatewayHost, const char *remoteHost,
245 int remotePort, int localPort)
246{
247 char *cmd = getenv ("VNC_VIA_CMD");
248 char *percent;
249 char lport[10], rport[10];
250 sprintf (lport, "%d", localPort);
251 sprintf (rport, "%d", remotePort);
252 setenv ("G", gatewayHost, 1);
253 setenv ("H", remoteHost, 1);
254 setenv ("R", rport, 1);
255 setenv ("L", lport, 1);
256 if (!cmd)
257 cmd = "/usr/bin/ssh -f -L \"$L\":\"$H\":\"$R\" \"$G\" sleep 20";
258 /* Compatibility with TightVNC's method. */
259 while ((percent = strchr (cmd, '%')) != NULL)
260 *percent = '$';
261 system (cmd);
262}
263
264int main(int argc, char** argv)
265{
266 setlocale(LC_ALL, "");
267 bindtextdomain(PACKAGE, LOCALEDIR);
268 textdomain(PACKAGE);
269
270 snprintf(aboutText, sizeof(aboutText),
Constantin Kaplinskyf4986f42006-06-02 10:49:03 +0000271 _("TightVNC Viewer for X version %s - built %s\n"
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000272 "Copyright (C) 2002-2005 RealVNC Ltd.\n"
Constantin Kaplinskyf4986f42006-06-02 10:49:03 +0000273 "Copyright (C) 2000-2006 TightVNC Group\n"
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000274 "Copyright (C) 2004-2005 Peter Astrand, Cendio AB\n"
275 "See http://www.tightvnc.com for information on TightVNC."),
Constantin Kaplinskyf4986f42006-06-02 10:49:03 +0000276 VERSION, buildtime);
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000277 fprintf(stderr,"\n%s\n", aboutText);
278
279 bind_textdomain_codeset(PACKAGE, "iso-8859-1");
280
281 rfb::initStdIOLoggers();
282 rfb::LogWriter::setLogParams("*:stderr:30");
283
284 signal(SIGHUP, CleanupSignalHandler);
285 signal(SIGINT, CleanupSignalHandler);
286 signal(SIGTERM, CleanupSignalHandler);
287
288 programName = argv[0];
289 char* vncServerName = 0;
290 Display* dpy = 0;
291
292 for (int i = 1; i < argc; i++) {
293 if (Configuration::setParam(argv[i]))
294 continue;
295
296 if (argv[i][0] == '-') {
297 if (i+1 < argc) {
298 if (Configuration::setParam(&argv[i][1], argv[i+1])) {
299 i++;
300 continue;
301 }
302 }
303 usage();
304 }
305
306 vncServerName = argv[i];
307 }
308
309 // Create .vnc in the user's home directory if it doesn't already exist
310 char* homeDir = getenv("HOME");
311 if (homeDir) {
312 CharArray vncDir(strlen(homeDir)+6);
313 sprintf(vncDir.buf, "%s/.vnc", homeDir);
314 int result = mkdir(vncDir.buf, 0755);
315 if (result == -1 && errno != EEXIST)
316 vlog.error("Could not create .vnc directory: %s.", strerror(errno));
317 } else
318 vlog.error("Could not create .vnc directory: environment variable $HOME not set.");
319
320 if (!::autoSelect.hasBeenSet()) {
321 // Default to AutoSelect=0 if -PreferredEncoding or -FullColor is used
322 ::autoSelect.setParam(!::preferredEncoding.hasBeenSet()
323 && !::fullColour.hasBeenSet()
324 && !::fullColourAlias.hasBeenSet());
325 }
326 if (!::customCompressLevel.hasBeenSet()) {
327 // Default to CustomCompressLevel=1 if CompressLevel is used.
328 ::customCompressLevel.setParam(::compressLevel.hasBeenSet());
329 }
330
331 try {
332 /* Tunnelling support. */
333 if (strlen (via.getValueStr ()) > 0) {
334 char *gatewayHost = "";
335 char *remoteHost = "localhost";
336 int localPort = findFreeTcpPort ();
337 int remotePort;
338 if (!vncServerName)
339 usage();
340 interpretViaParam (&gatewayHost, &remoteHost, &remotePort,
341 &vncServerName, localPort);
342 createTunnel (gatewayHost, remoteHost, remotePort, localPort);
343 }
344
345 Socket* sock = 0;
346
347 if (listenMode) {
348 int port = 5500;
349 if (vncServerName && isdigit(vncServerName[0]))
350 port = atoi(vncServerName);
351
352 TcpListener listener(port);
353
354 vlog.info("Listening on port %d\n",port);
355
356 while (true) {
357 sock = listener.accept();
358 int pid = fork();
359 if (pid < 0) { perror("fork"); exit(1); }
360 if (pid == 0) break; // child
361 delete sock;
362 int status;
363 while (wait3(&status, WNOHANG, 0) > 0) ;
364 }
365 }
366
367 CharArray displaynameStr(displayname.getData());
368 if (!(dpy = XOpenDisplay(TXWindow::strEmptyToNull(displaynameStr.buf)))) {
369 fprintf(stderr,"%s: unable to open display \"%s\"\n",
370 programName, XDisplayName(displaynameStr.buf));
371 exit(1);
372 }
373
374 TXWindow::init(dpy, "Vncviewer");
375 xloginIconifier.iconify(dpy);
376 CConn cc(dpy, argc, argv, sock, vncServerName, listenMode);
377
378 // X events are processed whenever reading from the socket would block.
379
380 while (true) {
381 cc.getInStream()->check(1);
382 cc.processMsg();
383 }
384
385 } catch (rdr::EndOfStream& e) {
386 vlog.info(e.str());
387 } catch (rdr::Exception& e) {
388 vlog.error(e.str());
389 if (dpy) {
390 TXMsgBox msgBox(dpy, e.str(), MB_OK, "VNC Viewer: Information");
391 msgBox.show();
392 }
393 return 1;
394 }
395
396 return 0;
397}