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