blob: a861f586d54cda1f416592b161035f190139cd6c [file] [log] [blame]
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +00001#!/usr/bin/env perl
2#
DRC190854c2009-03-26 18:13:00 +00003# Copyright (C) 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
4# Copyright (C) 2002-2003 Constantin Kaplinsky. All Rights Reserved.
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +00005# Copyright (C) 2002-2005 RealVNC Ltd.
6# Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
7#
8# This is free software; you can redistribute it and/or modify
9# it under the terms of the GNU General Public License as published by
10# the Free Software Foundation; either version 2 of the License, or
11# (at your option) any later version.
12#
13# This software is distributed in the hope that it will be useful,
14# but WITHOUT ANY WARRANTY; without even the implied warranty of
15# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16# GNU General Public License for more details.
17#
18# You should have received a copy of the GNU General Public License
19# along with this software; if not, write to the Free Software
20# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
21# USA.
22#
23
24#
25# vncserver - wrapper script to start an X VNC server.
26#
27
28#
29# First make sure we're operating in a sane environment.
30#
31
DRC190854c2009-03-26 18:13:00 +000032$exedir = "";
33$slashndx = rindex($0, "/");
34if($slashndx>=0) {
35 $exedir = substr($0, 0, $slashndx+1);
36}
37
38$vncClasses = "";
39
40$xauth = "xauth";
41
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000042&SanityCheck();
43
44#
45# Global variables. You may want to configure some of these for your site.
46#
47
48$geometry = "1024x768";
49$depth = 16;
50$vncJavaFiles = (((-d "/usr/share/vnc/classes") && "/usr/share/vnc/classes") ||
DRC190854c2009-03-26 18:13:00 +000051 ((-d "/usr/local/vnc/classes") && "/usr/local/vnc/classes") ||
52 ((-d "$vncClasses") && "$vncClasses"));
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000053$vncUserDir = "$ENV{HOME}/.vnc";
54$xauthorityFile = "$ENV{XAUTHORITY}" || "$ENV{HOME}/.Xauthority";
55
56$defaultXStartup
57 = ("#!/bin/sh\n\n".
DRC93248982009-03-26 18:14:38 +000058 "unset SESSION_MANAGER\n".
59 "OS=`uname -s`\n".
60 "if [ \$OS = 'Linux' ]; then\n".
61 " case \"\$WINDOWMANAGER\" in\n".
62 " \*gnome\*)\n".
63 " if [ -e /etc/SuSE-release ]; then\n".
64 " PATH=\$PATH:/opt/gnome/bin\n".
65 " export PATH\n".
66 " fi\n".
67 " ;;\n".
68 " esac\n".
69 "fi\n".
70 "if [ -x /etc/X11/xinit/xinitrc ]; then\n".
71 " exec /etc/X11/xinit/xinitrc\n".
72 "fi\n".
73 "if [ -f /etc/X11/xinit/xinitrc ]; then\n".
74 " exec sh /etc/X11/xinit/xinitrc\n".
75 "fi\n".
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +000076 "[ -r \$HOME/.Xresources ] && xrdb \$HOME/.Xresources\n".
77 "xsetroot -solid grey\n".
78 "vncconfig -iconic &\n".
79 "xterm -geometry 80x24+10+10 -ls -title \"\$VNCDESKTOP Desktop\" &\n".
80 "twm &\n");
81
82chop($host = `uname -n`);
83
84
85# Check command line options
86
87&ParseOptions("-geometry",1,"-depth",1,"-pixelformat",1,"-name",1,"-kill",1,
88 "-help",0,"-h",0,"--help",0);
89
90&Usage() if ($opt{'-help'} || $opt{'-h'} || $opt{'--help'});
91
92&Kill() if ($opt{'-kill'});
93
94# Uncomment this line if you want default geometry, depth and pixelformat
95# to match the current X display:
96# &GetXDisplayDefaults();
97
98if ($opt{'-geometry'}) {
99 $geometry = $opt{'-geometry'};
100}
101if ($opt{'-depth'}) {
102 $depth = $opt{'-depth'};
103 $pixelformat = "";
104}
105if ($opt{'-pixelformat'}) {
106 $pixelformat = $opt{'-pixelformat'};
107}
108
109&CheckGeometryAndDepth();
110
111
112# Create the user's vnc directory if necessary.
113
114if (!(-e $vncUserDir)) {
115 if (!mkdir($vncUserDir,0755)) {
116 die "$prog: Could not create $vncUserDir.\n";
117 }
118}
119
120# Make sure the user has a password.
121
122($z,$z,$mode) = stat("$vncUserDir/passwd");
123if (!(-e "$vncUserDir/passwd") || ($mode & 077)) {
124 warn "\nYou will require a password to access your desktops.\n\n";
DRC190854c2009-03-26 18:13:00 +0000125 system($exedir."vncpasswd -q $vncUserDir/passwd");
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000126 if (($? >> 8) != 0) {
127 exit 1;
128 }
129}
130
131# Find display number.
132
133if ((@ARGV > 0) && ($ARGV[0] =~ /^:(\d+)$/)) {
134 $displayNumber = $1;
135 shift(@ARGV);
136 if (!&CheckDisplayNumber($displayNumber)) {
137 die "A VNC server is already running as :$displayNumber\n";
138 }
139} elsif ((@ARGV > 0) && ($ARGV[0] !~ /^-/)) {
140 &Usage();
141} else {
142 $displayNumber = &GetDisplayNumber();
143}
144
145$vncPort = 5900 + $displayNumber;
146
147$desktopLog = "$vncUserDir/$host:$displayNumber.log";
148unlink($desktopLog);
149
150# Make an X server cookie - use as the seed the sum of the current time, our
151# PID and part of the encrypted form of the password. Ideally we'd use
152# /dev/urandom, but that's only available on Linux.
153
154srand(time+$$+unpack("L",`cat $vncUserDir/passwd`));
155$cookie = "";
156for (1..16) {
157 $cookie .= sprintf("%02x", int(rand(256)) % 256);
158}
159
160system("xauth -f $xauthorityFile add $host:$displayNumber . $cookie");
161system("xauth -f $xauthorityFile add $host/unix:$displayNumber . $cookie");
162
163if ($opt{'-name'}) {
164 $desktopName = $opt{'-name'};
165} else {
166 $desktopName = "$host:$displayNumber ($ENV{USER})";
167}
168
169# Now start the X VNC Server
170
DRC190854c2009-03-26 18:13:00 +0000171$cmd = $exedir."Xvnc :$displayNumber";
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000172$cmd .= " -desktop " . &quotedString($desktopName);
173$cmd .= " -httpd $vncJavaFiles" if ($vncJavaFiles);
174$cmd .= " -auth $xauthorityFile";
175$cmd .= " -geometry $geometry" if ($geometry);
176$cmd .= " -depth $depth" if ($depth);
177$cmd .= " -pixelformat $pixelformat" if ($pixelformat);
178$cmd .= " -rfbwait 30000";
179$cmd .= " -rfbauth $vncUserDir/passwd";
180$cmd .= " -rfbport $vncPort";
181$cmd .= " -pn";
182
183# Add font path and color database stuff here, e.g.:
184#
185# $cmd .= " -fp /usr/lib/X11/fonts/misc/,/usr/lib/X11/fonts/75dpi/";
186# $cmd .= " -co /usr/lib/X11/rgb";
187#
188
189foreach $arg (@ARGV) {
190 $cmd .= " " . &quotedString($arg);
191}
192$cmd .= " >> " . &quotedString($desktopLog) . " 2>&1";
193
194# Run $cmd and record the process ID.
195
196$pidFile = "$vncUserDir/$host:$displayNumber.pid";
197system("$cmd & echo \$! >$pidFile");
198
199# Give Xvnc a chance to start up
200
201sleep(3);
202
203warn "\nNew '$desktopName' desktop is $host:$displayNumber\n\n";
204
205# Create the user's xstartup script if necessary.
206
207if (!(-e "$vncUserDir/xstartup")) {
208 warn "Creating default startup script $vncUserDir/xstartup\n";
209 open(XSTARTUP, ">$vncUserDir/xstartup");
210 print XSTARTUP $defaultXStartup;
211 close(XSTARTUP);
212 chmod 0755, "$vncUserDir/xstartup";
213}
214
215# Run the X startup script.
216
217warn "Starting applications specified in $vncUserDir/xstartup\n";
218warn "Log file is $desktopLog\n\n";
219
220# If the unix domain socket exists then use that (DISPLAY=:n) otherwise use
221# TCP (DISPLAY=host:n)
222
223if (-e "/tmp/.X11-unix/X$displayNumber" ||
224 -e "/usr/spool/sockets/X11/$displayNumber")
225{
226 $ENV{DISPLAY}= ":$displayNumber";
227} else {
228 $ENV{DISPLAY}= "$host:$displayNumber";
229}
230$ENV{VNCDESKTOP}= $desktopName;
231
232system("$vncUserDir/xstartup >> " . &quotedString($desktopLog) . " 2>&1 &");
233
234exit;
235
236
237###############################################################################
238#
239# CheckGeometryAndDepth simply makes sure that the geometry and depth values
240# are sensible.
241#
242
243sub CheckGeometryAndDepth
244{
245 if ($geometry =~ /^(\d+)x(\d+)$/) {
246 $width = $1; $height = $2;
247
248 if (($width<1) || ($height<1)) {
249 die "$prog: geometry $geometry is invalid\n";
250 }
251
252 while (($width % 4)!=0) {
253 $width = $width + 1;
254 }
255
256 while (($height % 2)!=0) {
257 $height = $height + 1;
258 }
259
260 $geometry = "${width}x$height";
261 } else {
262 die "$prog: geometry $geometry is invalid\n";
263 }
264
265 if (($depth < 8) || ($depth > 32)) {
266 die "Depth must be between 8 and 32\n";
267 }
268}
269
270
271#
272# GetDisplayNumber gets the lowest available display number. A display number
273# n is taken if something is listening on the VNC server port (5900+n) or the
274# X server port (6000+n).
275#
276
277sub GetDisplayNumber
278{
279 foreach $n (1..99) {
280 if (&CheckDisplayNumber($n)) {
281 return $n+0; # Bruce Mah's workaround for bug in perl 5.005_02
282 }
283 }
284
285 die "$prog: no free display number on $host.\n";
286}
287
288
289#
290# CheckDisplayNumber checks if the given display number is available. A
291# display number n is taken if something is listening on the VNC server port
292# (5900+n) or the X server port (6000+n).
293#
294
295sub CheckDisplayNumber
296{
297 local ($n) = @_;
298
299 socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
300 eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
301 if (!bind(S, pack('S n x12', $AF_INET, 6000 + $n))) {
302 close(S);
303 return 0;
304 }
305 close(S);
306
307 socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
308 eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
309 if (!bind(S, pack('S n x12', $AF_INET, 5900 + $n))) {
310 close(S);
311 return 0;
312 }
313 close(S);
314
315 if (-e "/tmp/.X$n-lock") {
316 warn "\nWarning: $host:$n is taken because of /tmp/.X$n-lock\n";
317 warn "Remove this file if there is no X server $host:$n\n";
318 return 0;
319 }
320
321 if (-e "/tmp/.X11-unix/X$n") {
322 warn "\nWarning: $host:$n is taken because of /tmp/.X11-unix/X$n\n";
323 warn "Remove this file if there is no X server $host:$n\n";
324 return 0;
325 }
326
327 if (-e "/usr/spool/sockets/X11/$n") {
328 warn("\nWarning: $host:$n is taken because of ".
329 "/usr/spool/sockets/X11/$n\n");
330 warn "Remove this file if there is no X server $host:$n\n";
331 return 0;
332 }
333
334 return 1;
335}
336
337
338#
339# GetXDisplayDefaults uses xdpyinfo to find out the geometry, depth and pixel
340# format of the current X display being used. If successful, it sets the
341# options as appropriate so that the X VNC server will use the same settings
342# (minus an allowance for window manager decorations on the geometry). Using
343# the same depth and pixel format means that the VNC server won't have to
344# translate pixels when the desktop is being viewed on this X display (for
345# TrueColor displays anyway).
346#
347
348sub GetXDisplayDefaults
349{
350 local (@lines, @matchlines, $width, $height, $defaultVisualId, $i,
351 $red, $green, $blue);
352
353 $wmDecorationWidth = 4; # a guess at typical size for window manager
354 $wmDecorationHeight = 24; # decoration size
355
356 return if (!defined($ENV{DISPLAY}));
357
358 @lines = `xdpyinfo 2>/dev/null`;
359
360 return if ($? != 0);
361
362 @matchlines = grep(/dimensions/, @lines);
363 if (@matchlines) {
364 ($width, $height) = ($matchlines[0] =~ /(\d+)x(\d+) pixels/);
365
366 $width -= $wmDecorationWidth;
367 $height -= $wmDecorationHeight;
368
369 $geometry = "${width}x$height";
370 }
371
372 @matchlines = grep(/default visual id/, @lines);
373 if (@matchlines) {
374 ($defaultVisualId) = ($matchlines[0] =~ /id:\s+(\S+)/);
375
376 for ($i = 0; $i < @lines; $i++) {
377 if ($lines[$i] =~ /^\s*visual id:\s+$defaultVisualId$/) {
378 if (($lines[$i+1] !~ /TrueColor/) ||
379 ($lines[$i+2] !~ /depth/) ||
380 ($lines[$i+4] !~ /red, green, blue masks/))
381 {
382 return;
383 }
384 last;
385 }
386 }
387
388 return if ($i >= @lines);
389
390 ($depth) = ($lines[$i+2] =~ /depth:\s+(\d+)/);
391 ($red,$green,$blue)
392 = ($lines[$i+4]
393 =~ /masks:\s+0x([0-9a-f]+), 0x([0-9a-f]+), 0x([0-9a-f]+)/);
394
395 $red = hex($red);
396 $green = hex($green);
397 $blue = hex($blue);
398
399 if ($red > $blue) {
400 $red = int(log($red) / log(2)) - int(log($green) / log(2));
401 $green = int(log($green) / log(2)) - int(log($blue) / log(2));
402 $blue = int(log($blue) / log(2)) + 1;
403 $pixelformat = "rgb$red$green$blue";
404 } else {
405 $blue = int(log($blue) / log(2)) - int(log($green) / log(2));
406 $green = int(log($green) / log(2)) - int(log($red) / log(2));
407 $red = int(log($red) / log(2)) + 1;
408 $pixelformat = "bgr$blue$green$red";
409 }
410 }
411}
412
413
414#
415# quotedString returns a string which yields the original string when parsed
416# by a shell.
417#
418
419sub quotedString
420{
421 local ($in) = @_;
422
423 $in =~ s/\'/\'\"\'\"\'/g;
424
425 return "'$in'";
426}
427
428
429#
430# removeSlashes turns slashes into underscores for use as a file name.
431#
432
433sub removeSlashes
434{
435 local ($in) = @_;
436
437 $in =~ s|/|_|g;
438
439 return "$in";
440}
441
442
443#
444# Usage
445#
446
447sub Usage
448{
449 die("\nusage: $prog [:<number>] [-name <desktop-name>] [-depth <depth>]\n".
450 " [-geometry <width>x<height>]\n".
451 " [-pixelformat rgbNNN|bgrNNN]\n".
452 " <Xvnc-options>...\n\n".
453 " $prog -kill <X-display>\n\n");
454}
455
456
457#
458# Kill
459#
460
461sub Kill
462{
463 $opt{'-kill'} =~ s/(:\d+)\.\d+$/$1/; # e.g. turn :1.0 into :1
464
465 if ($opt{'-kill'} =~ /^:\d+$/) {
466 $pidFile = "$vncUserDir/$host$opt{'-kill'}.pid";
467 } else {
468 if ($opt{'-kill'} !~ /^$host:/) {
469 die "\nCan't tell if $opt{'-kill'} is on $host\n".
470 "Use -kill :<number> instead\n\n";
471 }
472 $pidFile = "$vncUserDir/$opt{'-kill'}.pid";
473 }
474
475 if (! -r $pidFile) {
476 die "\nCan't find file $pidFile\n".
477 "You'll have to kill the Xvnc process manually\n\n";
478 }
479
480 $SIG{'HUP'} = 'IGNORE';
481 chop($pid = `cat $pidFile`);
482 warn "Killing Xvnc process ID $pid\n";
483 system("kill $pid");
484 unlink $pidFile;
485 exit;
486}
487
488
489#
490# ParseOptions takes a list of possible options and a boolean indicating
491# whether the option has a value following, and sets up an associative array
492# %opt of the values of the options given on the command line. It removes all
493# the arguments it uses from @ARGV and returns them in @optArgs.
494#
495
496sub ParseOptions
497{
498 local (@optval) = @_;
499 local ($opt, @opts, %valFollows, @newargs);
500
501 while (@optval) {
502 $opt = shift(@optval);
503 push(@opts,$opt);
504 $valFollows{$opt} = shift(@optval);
505 }
506
507 @optArgs = ();
508 %opt = ();
509
510 arg: while (defined($arg = shift(@ARGV))) {
511 foreach $opt (@opts) {
512 if ($arg eq $opt) {
513 push(@optArgs, $arg);
514 if ($valFollows{$opt}) {
515 if (@ARGV == 0) {
516 &Usage();
517 }
518 $opt{$opt} = shift(@ARGV);
519 push(@optArgs, $opt{$opt});
520 } else {
521 $opt{$opt} = 1;
522 }
523 next arg;
524 }
525 }
526 push(@newargs,$arg);
527 }
528
529 @ARGV = @newargs;
530}
531
532
533#
534# Routine to make sure we're operating in a sane environment.
535#
536
537sub SanityCheck
538{
539 local ($cmd);
540
541 #
542 # Get the program name
543 #
544
545 ($prog) = ($0 =~ m|([^/]+)$|);
546
547 #
548 # Check we have all the commands we'll need on the path.
549 #
550
551 cmd:
DRC190854c2009-03-26 18:13:00 +0000552 foreach $cmd ("uname") {
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000553 for (split(/:/,$ENV{PATH})) {
554 if (-x "$_/$cmd") {
555 next cmd;
556 }
557 }
558 die "$prog: couldn't find \"$cmd\" on your PATH.\n";
559 }
DRC190854c2009-03-26 18:13:00 +0000560 if (-x "/usr/X11R6/bin/xauth") {
561 $xauth = "/usr/X11R6/bin/xauth";
562 }
563 else {
564 cmd1:
565 foreach $cmd ("xauth") {
566 for (split(/:/,$ENV{PATH})) {
567 if (-x "$_/$cmd") {
568 next cmd1;
569 }
570 }
571 die "$prog: couldn't find \"$cmd\" on your PATH.\n";
572 }
573 }
574
575 if($exedir eq "") {
576 cmd2:
577 foreach $cmd ("Xvnc","vncpasswd") {
578 for (split(/:/,$ENV{PATH})) {
579 if (-x "$_/$cmd") {
580 $vncClasses = "$_/../vnc/classes";
581 next cmd2;
582 }
583 }
584 die "$prog: couldn't find \"$cmd\" on your PATH.\n";
585 }
586 }
587 else {
588 cmd3:
589 foreach $cmd ($exedir."Xvnc",$exedir."vncpasswd") {
590 for (split(/:/,$ENV{PATH})) {
591 if (-x "$cmd") {
592 $vncClasses = $exedir."../vnc/classes";
593 next cmd3;
594 }
595 }
596 die "$prog: couldn't find \"$cmd\".\n";
597 }
598 }
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000599
600 #
601 # Check the HOME environment variable is set
602 #
603
604 if (!defined($ENV{HOME})) {
605 die "$prog: The HOME environment variable is not set.\n";
606 }
DRC190854c2009-03-26 18:13:00 +0000607# chdir($ENV{HOME});
Constantin Kaplinskyb30ae7f2006-05-25 05:04:46 +0000608
609 #
610 # Find socket constants. 'use Socket' is a perl5-ism, so we wrap it in an
611 # eval, and if it fails we try 'require "sys/socket.ph"'. If this fails,
612 # we just guess at the values. If you find perl moaning here, just
613 # hard-code the values of AF_INET and SOCK_STREAM. You can find these out
614 # for your platform by looking in /usr/include/sys/socket.h and related
615 # files.
616 #
617
618 chop($os = `uname`);
619 chop($osrev = `uname -r`);
620
621 eval 'use Socket';
622 if ($@) {
623 eval 'require "sys/socket.ph"';
624 if ($@) {
625 if (($os eq "SunOS") && ($osrev !~ /^4/)) {
626 $AF_INET = 2;
627 $SOCK_STREAM = 2;
628 } else {
629 $AF_INET = 2;
630 $SOCK_STREAM = 1;
631 }
632 } else {
633 $AF_INET = &AF_INET;
634 $SOCK_STREAM = &SOCK_STREAM;
635 }
636 } else {
637 $AF_INET = &AF_INET;
638 $SOCK_STREAM = &SOCK_STREAM;
639 }
640}