You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vncserver 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. #!/usr/bin/env perl
  2. #
  3. # Copyright (C) 2009-2010 D. R. Commander. All Rights Reserved.
  4. # Copyright (C) 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
  5. # Copyright (C) 2002-2003 Constantin Kaplinsky. All Rights Reserved.
  6. # Copyright (C) 2002-2005 RealVNC Ltd.
  7. # Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
  8. #
  9. # This is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This software is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License
  20. # along with this software; if not, write to the Free Software
  21. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
  22. # USA.
  23. #
  24. #
  25. # vncserver - wrapper script to start an X VNC server.
  26. #
  27. # First make sure we're operating in a sane environment.
  28. $exedir = "";
  29. $slashndx = rindex($0, "/");
  30. if($slashndx>=0) {
  31. $exedir = substr($0, 0, $slashndx+1);
  32. }
  33. $vncClasses = "";
  34. &SanityCheck();
  35. #
  36. # Global variables. You may want to configure some of these for
  37. # your site
  38. #
  39. $geometry = "1024x768";
  40. #$depth = 16;
  41. $vncJavaFiles = (((-d "$vncClasses") && "$vncClasses") ||
  42. ((-d "/usr/share/vnc/classes") && "/usr/share/vnc/classes") ||
  43. ((-d "/usr/local/vnc/classes") && "/usr/local/vnc/classes"));
  44. $vncUserDir = "$ENV{HOME}/.vnc";
  45. $vncUserConfig = "$vncUserDir/config";
  46. $vncSystemConfigDir = "/etc/tigervnc";
  47. $vncSystemConfigDefaultsFile = "$vncSystemConfigDir/vncserver-config-defaults";
  48. $vncSystemConfigMandatoryFile = "$vncSystemConfigDir/vncserver-config-mandatory";
  49. $skipxstartup = 0;
  50. $xauthorityFile = "$ENV{XAUTHORITY}" || "$ENV{HOME}/.Xauthority";
  51. $xstartupFile = $vncUserDir . "/xstartup";
  52. $defaultXStartup
  53. = ("#!/bin/sh\n\n".
  54. "unset SESSION_MANAGER\n".
  55. "unset DBUS_SESSION_BUS_ADDRESS\n".
  56. "OS=`uname -s`\n".
  57. "if [ \$OS = 'Linux' ]; then\n".
  58. " case \"\$WINDOWMANAGER\" in\n".
  59. " \*gnome\*)\n".
  60. " if [ -e /etc/SuSE-release ]; then\n".
  61. " PATH=\$PATH:/opt/gnome/bin\n".
  62. " export PATH\n".
  63. " fi\n".
  64. " ;;\n".
  65. " esac\n".
  66. "fi\n".
  67. "if [ -x /etc/X11/xinit/xinitrc ]; then\n".
  68. " exec /etc/X11/xinit/xinitrc\n".
  69. "fi\n".
  70. "if [ -f /etc/X11/xinit/xinitrc ]; then\n".
  71. " exec sh /etc/X11/xinit/xinitrc\n".
  72. "fi\n".
  73. "[ -r \$HOME/.Xresources ] && xrdb \$HOME/.Xresources\n".
  74. "xsetroot -solid grey\n".
  75. "xterm -geometry 80x24+10+10 -ls -title \"\$VNCDESKTOP Desktop\" &\n".
  76. "twm &\n");
  77. $defaultConfig
  78. = ("## Supported server options to pass to vncserver upon invocation can be listed\n".
  79. "## in this file. See the following manpages for more: vncserver(1) Xvnc(1).\n".
  80. "## Several common ones are shown below. Uncomment and modify to your liking.\n".
  81. "##\n".
  82. "# securitytypes=vncauth,tlsvnc\n".
  83. "# desktop=sandbox\n".
  84. "# geometry=2000x1200\n".
  85. "# localhost\n".
  86. "# alwaysshared\n");
  87. chop($host = `uname -n`);
  88. if (-d "/etc/X11/fontpath.d") {
  89. $fontPath = "catalogue:/etc/X11/fontpath.d";
  90. }
  91. @fontpaths = ('/usr/share/X11/fonts', '/usr/share/fonts', '/usr/share/fonts/X11/');
  92. if (! -l "/usr/lib/X11") {push(@fontpaths, '/usr/lib/X11/fonts');}
  93. if (! -l "/usr/X11") {push(@fontpaths, '/usr/X11/lib/X11/fonts');}
  94. if (! -l "/usr/X11R6") {push(@fontpaths, '/usr/X11R6/lib/X11/fonts');}
  95. push(@fontpaths, '/usr/share/fonts/default');
  96. @fonttypes = ('misc',
  97. '75dpi',
  98. '100dpi',
  99. 'Speedo',
  100. 'Type1');
  101. foreach $_fpath (@fontpaths) {
  102. foreach $_ftype (@fonttypes) {
  103. if (-f "$_fpath/$_ftype/fonts.dir") {
  104. if (! -l "$_fpath/$_ftype") {
  105. $defFontPath .= "$_fpath/$_ftype,";
  106. }
  107. }
  108. }
  109. }
  110. if ($defFontPath) {
  111. if (substr($defFontPath, -1, 1) == ',') {
  112. chop $defFontPath;
  113. }
  114. }
  115. if ($fontPath eq "") {
  116. $fontPath = $defFontPath;
  117. }
  118. # Check command line options
  119. &ParseOptions("-geometry",1,"-depth",1,"-pixelformat",1,"-name",1,"-kill",1,
  120. "-help",0,"-h",0,"--help",0,"-fp",1,"-list",0,"-fg",0,"-autokill",0,"-noxstartup",0,"-xstartup",1);
  121. &Usage() if ($opt{'-help'} || $opt{'-h'} || $opt{'--help'});
  122. &Kill() if ($opt{'-kill'});
  123. &List() if ($opt{'-list'});
  124. # Uncomment this line if you want default geometry, depth and pixelformat
  125. # to match the current X display:
  126. # &GetXDisplayDefaults();
  127. if ($opt{'-geometry'}) {
  128. $geometry = $opt{'-geometry'};
  129. }
  130. if ($opt{'-depth'}) {
  131. $depth = $opt{'-depth'};
  132. $pixelformat = "";
  133. }
  134. if ($opt{'-pixelformat'}) {
  135. $pixelformat = $opt{'-pixelformat'};
  136. }
  137. if ($opt{'-noxstartup'}) {
  138. $skipxstartup = 1;
  139. }
  140. if ($opt{'-xstartup'}) {
  141. $xstartupFile = $opt{'-xstartup'};
  142. }
  143. if ($opt{'-fp'}) {
  144. $fontPath = $opt{'-fp'};
  145. $fpArgSpecified = 1;
  146. }
  147. &CheckGeometryAndDepth();
  148. # Create the user's vnc directory if necessary.
  149. if (!(-e $vncUserDir)) {
  150. if (!mkdir($vncUserDir,0755)) {
  151. die "$prog: Could not create $vncUserDir.\n";
  152. }
  153. }
  154. # Find display number.
  155. if ((@ARGV > 0) && ($ARGV[0] =~ /^:(\d+)$/)) {
  156. $displayNumber = $1;
  157. shift(@ARGV);
  158. if (!&CheckDisplayNumber($displayNumber)) {
  159. die "A VNC server is already running as :$displayNumber\n";
  160. }
  161. } elsif ((@ARGV > 0) && ($ARGV[0] !~ /^-/) && ($ARGV[0] !~ /^\+/)) {
  162. &Usage();
  163. } else {
  164. $displayNumber = &GetDisplayNumber();
  165. }
  166. $vncPort = 5900 + $displayNumber;
  167. if ($opt{'-name'}) {
  168. $desktopName = $opt{'-name'};
  169. } else {
  170. $desktopName = "$host:$displayNumber ($ENV{USER})";
  171. }
  172. my %default_opts;
  173. my %config;
  174. # We set some reasonable defaults. Config file settings
  175. # override these where present.
  176. $default_opts{desktop} = &quotedString($desktopName);
  177. $default_opts{httpd} = $vncJavaFiles if ($vncJavaFiles);
  178. $default_opts{auth} = &quotedString($xauthorityFile);
  179. $default_opts{geometry} = $geometry if ($geometry);
  180. $default_opts{depth} = $depth if ($depth);
  181. $default_opts{pixelformat} = $pixelformat if ($pixelformat);
  182. $default_opts{rfbwait} = 30000;
  183. $default_opts{rfbauth} = "$vncUserDir/passwd";
  184. $default_opts{rfbport} = $vncPort;
  185. $default_opts{fp} = $fontPath if ($fontPath);
  186. $default_opts{pn} = "";
  187. # Load user-overrideable system defaults
  188. LoadConfig($vncSystemConfigDefaultsFile);
  189. # Then the user's settings
  190. LoadConfig($vncUserConfig);
  191. # And then override anything set above if mandatory settings exist.
  192. # WARNING: "Mandatory" is used loosely here! As the man page says,
  193. # there is nothing stopping someone from EASILY subverting the
  194. # settings in $vncSystemConfigMandatoryFile by simply passing
  195. # CLI args to vncserver, which trump config files! To properly
  196. # hard force policy in a non-subvertible way would require major
  197. # development work that touches Xvnc itself.
  198. LoadConfig($vncSystemConfigMandatoryFile, 1);
  199. #
  200. # Check whether VNC authentication is enabled, and if so, prompt the user to
  201. # create a VNC password if they don't already have one.
  202. #
  203. $securityTypeArgSpecified = 0;
  204. $vncAuthEnabled = 0;
  205. $passwordArgSpecified = 0;
  206. @vncAuthStrings = ("vncauth", "tlsvnc", "x509vnc");
  207. # ...first we check our configuration files' settings
  208. if ($config{'securitytypes'}) {
  209. $securityTypeArgSpecified = 1;
  210. foreach $arg2 (split(',', $config{'securitytypes'})) {
  211. if (grep {$_ eq lc($arg2)} @vncAuthStrings) {
  212. $vncAuthEnabled = 1;
  213. }
  214. }
  215. }
  216. # ...and finally we check CLI args, which in the case of the topic at
  217. # hand (VNC auth or not), override anything found in configuration files
  218. # (even so-called "mandatory" settings).
  219. for ($i = 0; $i < @ARGV; ++$i) {
  220. # -SecurityTypes can be followed by a space or "="
  221. my @splitargs = split('=', $ARGV[$i]);
  222. if (@splitargs <= 1 && $i < @ARGV - 1) {
  223. push(@splitargs, $ARGV[$i + 1]);
  224. }
  225. if (lc(@splitargs[0]) eq "-securitytypes") {
  226. if (@splitargs > 1) {
  227. $securityTypeArgSpecified = 1;
  228. }
  229. foreach $arg2 (split(',', @splitargs[1])) {
  230. if (grep {$_ eq lc($arg2)} @vncAuthStrings) {
  231. $vncAuthEnabled = 1;
  232. }
  233. }
  234. }
  235. if ((lc(@splitargs[0]) eq "-password")
  236. || (lc(@splitargs[0]) eq "-passwordfile"
  237. || (lc(@splitargs[0]) eq "-rfbauth"))) {
  238. $passwordArgSpecified = 1;
  239. }
  240. }
  241. if ((!$securityTypeArgSpecified || $vncAuthEnabled) && !$passwordArgSpecified) {
  242. ($z,$z,$mode) = stat("$vncUserDir/passwd");
  243. if (!(-e "$vncUserDir/passwd") || ($mode & 077)) {
  244. warn "\nYou will require a password to access your desktops.\n\n";
  245. system($exedir."vncpasswd -q $vncUserDir/passwd");
  246. if (($? >> 8) != 0) {
  247. exit 1;
  248. }
  249. }
  250. }
  251. $desktopLog = "$vncUserDir/$host:$displayNumber.log";
  252. unlink($desktopLog);
  253. # Make an X server cookie and set up the Xauthority file
  254. # mcookie is a part of util-linux, usually only GNU/Linux systems have it.
  255. $cookie = `mcookie`;
  256. # Fallback for non GNU/Linux OS - use /dev/urandom on systems that have it,
  257. # otherwise use perl's random number generator, seeded with the sum
  258. # of the current time, our PID and part of the encrypted form of the password.
  259. if ($cookie eq "" && open(URANDOM, '<', '/dev/urandom')) {
  260. my $randata;
  261. if (sysread(URANDOM, $randata, 16) == 16) {
  262. $cookie = unpack 'h*', $randata;
  263. }
  264. close(URANDOM);
  265. }
  266. if ($cookie eq "") {
  267. srand(time+$$+unpack("L",`cat $vncUserDir/passwd`));
  268. for (1..16) {
  269. $cookie .= sprintf("%02x", int(rand(256)) % 256);
  270. }
  271. }
  272. open(XAUTH, "|xauth -f $xauthorityFile source -");
  273. print XAUTH "add $host:$displayNumber . $cookie\n";
  274. print XAUTH "add $host/unix:$displayNumber . $cookie\n";
  275. close(XAUTH);
  276. # Now start the X VNC Server
  277. # We build up our Xvnc command with options
  278. $cmd = $exedir."Xvnc :$displayNumber";
  279. foreach my $k (sort keys %config) {
  280. $cmd .= " -$k $config{$k}";
  281. delete $default_opts{$k}; # file options take precedence
  282. }
  283. foreach my $k (sort keys %default_opts) {
  284. $cmd .= " -$k $default_opts{$k}";
  285. }
  286. # Add color database stuff here, e.g.:
  287. # $cmd .= " -co /usr/lib/X11/rgb";
  288. foreach $arg (@ARGV) {
  289. $cmd .= " " . &quotedString($arg);
  290. }
  291. $cmd .= " >> " . &quotedString($desktopLog) . " 2>&1";
  292. # Run $cmd and record the process ID.
  293. $pidFile = "$vncUserDir/$host:$displayNumber.pid";
  294. system("$cmd & echo \$! >$pidFile");
  295. # Give Xvnc a chance to start up
  296. sleep(3);
  297. if ($fontPath ne $defFontPath) {
  298. unless (kill 0, `cat $pidFile`) {
  299. if ($fpArgSpecified) {
  300. warn "\nWARNING: The first attempt to start Xvnc failed, probably because the font\n";
  301. warn "path you specified using the -fp argument is incorrect. Attempting to\n";
  302. warn "determine an appropriate font path for this system and restart Xvnc using\n";
  303. warn "that font path ...\n";
  304. } else {
  305. warn "\nWARNING: The first attempt to start Xvnc failed, possibly because the font\n";
  306. warn "catalog is not properly configured. Attempting to determine an appropriate\n";
  307. warn "font path for this system and restart Xvnc using that font path ...\n";
  308. }
  309. $cmd =~ s@-fp [^ ]+@@;
  310. $cmd .= " -fp $defFontPath" if ($defFontPath);
  311. system("$cmd & echo \$! >$pidFile");
  312. sleep(3);
  313. }
  314. }
  315. unless (kill 0, `cat $pidFile`) {
  316. warn "Could not start Xvnc.\n\n";
  317. unlink $pidFile;
  318. open(LOG, "<$desktopLog");
  319. while (<LOG>) { print; }
  320. close(LOG);
  321. die "\n";
  322. }
  323. warn "\nNew '$desktopName' desktop is $host:$displayNumber\n\n";
  324. # Create the user's xstartup script if necessary.
  325. if (! $skipxstartup) {
  326. if (!(-e "$xstartupFile")) {
  327. warn "Creating default startup script $xstartupFile\n";
  328. open(XSTARTUP, ">$xstartupFile");
  329. print XSTARTUP $defaultXStartup;
  330. close(XSTARTUP);
  331. chmod 0755, "$xstartupFile";
  332. }
  333. }
  334. # Create the user's config file if necessary.
  335. if (!(-e "$vncUserDir/config")) {
  336. warn "Creating default config $vncUserDir/config\n";
  337. open(VNCUSERCONFIG, ">$vncUserDir/config");
  338. print VNCUSERCONFIG $defaultConfig;
  339. close(VNCUSERCONFIG);
  340. chmod 0644, "$vncUserDir/config";
  341. }
  342. # Run the X startup script.
  343. if (! $skipxstartup) {
  344. warn "Starting applications specified in $xstartupFile\n";
  345. }
  346. warn "Log file is $desktopLog\n\n";
  347. # If the unix domain socket exists then use that (DISPLAY=:n) otherwise use
  348. # TCP (DISPLAY=host:n)
  349. if (-e "/tmp/.X11-unix/X$displayNumber" ||
  350. -e "/usr/spool/sockets/X11/$displayNumber")
  351. {
  352. $ENV{DISPLAY}= ":$displayNumber";
  353. } else {
  354. $ENV{DISPLAY}= "$host:$displayNumber";
  355. }
  356. $ENV{VNCDESKTOP}= $desktopName;
  357. if ($opt{'-fg'}) {
  358. if (! $skipxstartup) {
  359. system("$xstartupFile >> " . &quotedString($desktopLog) . " 2>&1");
  360. }
  361. if (kill 0, `cat $pidFile`) {
  362. $opt{'-kill'} = ':'.$displayNumber;
  363. &Kill();
  364. }
  365. } else {
  366. if ($opt{'-autokill'}) {
  367. if (! $skipxstartup) {
  368. system("($xstartupFile; $0 -kill :$displayNumber) >> "
  369. . &quotedString($desktopLog) . " 2>&1 &");
  370. }
  371. } else {
  372. if (! $skipxstartup) {
  373. system("$xstartupFile >> " . &quotedString($desktopLog)
  374. . " 2>&1 &");
  375. }
  376. }
  377. }
  378. exit;
  379. ###############################################################################
  380. # Functions
  381. ###############################################################################
  382. #
  383. # Populate the global %config hash with settings from a specified
  384. # vncserver configuration file if it exists
  385. #
  386. # Args: 1. file path
  387. # 2. optional boolean flag to enable warning when a previously
  388. # set configuration setting is being overridden
  389. #
  390. sub LoadConfig {
  391. local ($configFile, $warnoverride) = @_;
  392. local ($toggle) = undef;
  393. if (stat($configFile)) {
  394. if (open(IN, $configFile)) {
  395. while (<IN>) {
  396. next if /^#/;
  397. if (my ($k, $v) = /^\s*(\w+)\s*=\s*(.+)$/) {
  398. $k = lc($k); # must normalize key case
  399. if ($warnoverride && $config{$k}) {
  400. print("Warning: $configFile is overriding previously defined '$k' to be '$v'\n");
  401. }
  402. $config{$k} = $v;
  403. } elsif ($_ =~ m/^\s*(\S+)/) {
  404. # We can't reasonably warn on override of toggles (e.g. AlwaysShared)
  405. # because it would get crazy to do so. We'd have to check if the
  406. # current config file being loaded defined the logical opposite setting
  407. # (NeverShared vs. AlwaysShared, etc etc).
  408. $toggle = lc($1); # must normalize key case
  409. $config{$toggle} = $k;
  410. }
  411. }
  412. close(IN);
  413. }
  414. }
  415. }
  416. #
  417. # CheckGeometryAndDepth simply makes sure that the geometry and depth values
  418. # are sensible.
  419. #
  420. sub CheckGeometryAndDepth
  421. {
  422. if ($geometry =~ /^(\d+)x(\d+)$/) {
  423. $width = $1; $height = $2;
  424. if (($width<1) || ($height<1)) {
  425. die "$prog: geometry $geometry is invalid\n";
  426. }
  427. $geometry = "${width}x$height";
  428. } else {
  429. die "$prog: geometry $geometry is invalid\n";
  430. }
  431. if ($depth && (($depth < 8) || ($depth > 32))) {
  432. die "Depth must be between 8 and 32\n";
  433. }
  434. }
  435. #
  436. # GetDisplayNumber gets the lowest available display number. A display number
  437. # n is taken if something is listening on the VNC server port (5900+n) or the
  438. # X server port (6000+n).
  439. #
  440. sub GetDisplayNumber
  441. {
  442. foreach $n (1..99) {
  443. if (&CheckDisplayNumber($n)) {
  444. return $n+0; # Bruce Mah's workaround for bug in perl 5.005_02
  445. }
  446. }
  447. die "$prog: no free display number on $host.\n";
  448. }
  449. #
  450. # CheckDisplayNumber checks if the given display number is available. A
  451. # display number n is taken if something is listening on the VNC server port
  452. # (5900+n) or the X server port (6000+n).
  453. #
  454. sub CheckDisplayNumber
  455. {
  456. local ($n) = @_;
  457. socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
  458. eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
  459. if (!bind(S, pack('S n x12', $AF_INET, 6000 + $n))) {
  460. close(S);
  461. return 0;
  462. }
  463. close(S);
  464. socket(S, $AF_INET, $SOCK_STREAM, 0) || die "$prog: socket failed: $!\n";
  465. eval 'setsockopt(S, &SOL_SOCKET, &SO_REUSEADDR, pack("l", 1))';
  466. if (!bind(S, pack('S n x12', $AF_INET, 5900 + $n))) {
  467. close(S);
  468. return 0;
  469. }
  470. close(S);
  471. if (-e "/tmp/.X$n-lock") {
  472. warn "\nWarning: $host:$n is taken because of /tmp/.X$n-lock\n";
  473. warn "Remove this file if there is no X server $host:$n\n";
  474. return 0;
  475. }
  476. if (-e "/tmp/.X11-unix/X$n") {
  477. warn "\nWarning: $host:$n is taken because of /tmp/.X11-unix/X$n\n";
  478. warn "Remove this file if there is no X server $host:$n\n";
  479. return 0;
  480. }
  481. if (-e "/usr/spool/sockets/X11/$n") {
  482. warn("\nWarning: $host:$n is taken because of ".
  483. "/usr/spool/sockets/X11/$n\n");
  484. warn "Remove this file if there is no X server $host:$n\n";
  485. return 0;
  486. }
  487. return 1;
  488. }
  489. #
  490. # GetXDisplayDefaults uses xdpyinfo to find out the geometry, depth and pixel
  491. # format of the current X display being used. If successful, it sets the
  492. # options as appropriate so that the X VNC server will use the same settings
  493. # (minus an allowance for window manager decorations on the geometry). Using
  494. # the same depth and pixel format means that the VNC server won't have to
  495. # translate pixels when the desktop is being viewed on this X display (for
  496. # TrueColor displays anyway).
  497. #
  498. sub GetXDisplayDefaults
  499. {
  500. local (@lines, @matchlines, $width, $height, $defaultVisualId, $i,
  501. $red, $green, $blue);
  502. $wmDecorationWidth = 4; # a guess at typical size for window manager
  503. $wmDecorationHeight = 24; # decoration size
  504. return if (!defined($ENV{DISPLAY}));
  505. @lines = `xdpyinfo 2>/dev/null`;
  506. return if ($? != 0);
  507. @matchlines = grep(/dimensions/, @lines);
  508. if (@matchlines) {
  509. ($width, $height) = ($matchlines[0] =~ /(\d+)x(\d+) pixels/);
  510. $width -= $wmDecorationWidth;
  511. $height -= $wmDecorationHeight;
  512. $geometry = "${width}x$height";
  513. }
  514. @matchlines = grep(/default visual id/, @lines);
  515. if (@matchlines) {
  516. ($defaultVisualId) = ($matchlines[0] =~ /id:\s+(\S+)/);
  517. for ($i = 0; $i < @lines; $i++) {
  518. if ($lines[$i] =~ /^\s*visual id:\s+$defaultVisualId$/) {
  519. if (($lines[$i+1] !~ /TrueColor/) ||
  520. ($lines[$i+2] !~ /depth/) ||
  521. ($lines[$i+4] !~ /red, green, blue masks/))
  522. {
  523. return;
  524. }
  525. last;
  526. }
  527. }
  528. return if ($i >= @lines);
  529. ($depth) = ($lines[$i+2] =~ /depth:\s+(\d+)/);
  530. ($red,$green,$blue)
  531. = ($lines[$i+4]
  532. =~ /masks:\s+0x([0-9a-f]+), 0x([0-9a-f]+), 0x([0-9a-f]+)/);
  533. $red = hex($red);
  534. $green = hex($green);
  535. $blue = hex($blue);
  536. if ($red > $blue) {
  537. $red = int(log($red) / log(2)) - int(log($green) / log(2));
  538. $green = int(log($green) / log(2)) - int(log($blue) / log(2));
  539. $blue = int(log($blue) / log(2)) + 1;
  540. $pixelformat = "rgb$red$green$blue";
  541. } else {
  542. $blue = int(log($blue) / log(2)) - int(log($green) / log(2));
  543. $green = int(log($green) / log(2)) - int(log($red) / log(2));
  544. $red = int(log($red) / log(2)) + 1;
  545. $pixelformat = "bgr$blue$green$red";
  546. }
  547. }
  548. }
  549. #
  550. # quotedString returns a string which yields the original string when parsed
  551. # by a shell.
  552. #
  553. sub quotedString
  554. {
  555. local ($in) = @_;
  556. $in =~ s/\'/\'\"\'\"\'/g;
  557. return "'$in'";
  558. }
  559. #
  560. # removeSlashes turns slashes into underscores for use as a file name.
  561. #
  562. sub removeSlashes
  563. {
  564. local ($in) = @_;
  565. $in =~ s|/|_|g;
  566. return "$in";
  567. }
  568. #
  569. # Usage
  570. #
  571. sub Usage
  572. {
  573. die("\nusage: $prog [:<number>] [-name <desktop-name>] [-depth <depth>]\n".
  574. " [-geometry <width>x<height>]\n".
  575. " [-pixelformat rgbNNN|bgrNNN]\n".
  576. " [-fp <font-path>]\n".
  577. " [-fg]\n".
  578. " [-autokill]\n".
  579. " [-noxstartup]\n".
  580. " [-xstartup <file>]\n".
  581. " <Xvnc-options>...\n\n".
  582. " $prog -kill <X-display>\n\n".
  583. " $prog -list\n\n");
  584. }
  585. #
  586. # List
  587. #
  588. sub List
  589. {
  590. opendir(dir, $vncUserDir);
  591. my @filelist = readdir(dir);
  592. closedir(dir);
  593. print "\nTigerVNC server sessions:\n\n";
  594. print "X DISPLAY #\tPROCESS ID\n";
  595. foreach my $file (@filelist) {
  596. if ($file =~ /$host:(\d+)$\.pid/) {
  597. chop($tmp_pid = `cat $vncUserDir/$file`);
  598. if (kill 0, $tmp_pid) {
  599. print ":".$1."\t\t".`cat $vncUserDir/$file`;
  600. } else {
  601. unlink ($vncUserDir . "/" . $file);
  602. }
  603. }
  604. }
  605. exit 1;
  606. }
  607. #
  608. # Kill
  609. #
  610. sub Kill
  611. {
  612. $opt{'-kill'} =~ s/(:\d+)\.\d+$/$1/; # e.g. turn :1.0 into :1
  613. if ($opt{'-kill'} =~ /^:\d+$/) {
  614. $pidFile = "$vncUserDir/$host$opt{'-kill'}.pid";
  615. } else {
  616. if ($opt{'-kill'} !~ /^$host:/) {
  617. die "\nCan't tell if $opt{'-kill'} is on $host\n".
  618. "Use -kill :<number> instead\n\n";
  619. }
  620. $pidFile = "$vncUserDir/$opt{'-kill'}.pid";
  621. }
  622. if (! -r $pidFile) {
  623. die "\nCan't find file $pidFile\n".
  624. "You'll have to kill the Xvnc process manually\n\n";
  625. }
  626. $SIG{'HUP'} = 'IGNORE';
  627. chop($pid = `cat $pidFile`);
  628. warn "Killing Xvnc process ID $pid\n";
  629. if (kill 0, $pid) {
  630. system("kill $pid");
  631. sleep(1);
  632. if (kill 0, $pid) {
  633. print "Xvnc seems to be deadlocked. Kill the process manually and then re-run\n";
  634. print " ".$0." -kill ".$opt{'-kill'}."\n";
  635. print "to clean up the socket files.\n";
  636. exit
  637. }
  638. } else {
  639. warn "Xvnc process ID $pid already killed\n";
  640. $opt{'-kill'} =~ s/://;
  641. if (-e "/tmp/.X11-unix/X$opt{'-kill'}") {
  642. print "Xvnc did not appear to shut down cleanly.";
  643. print " Removing /tmp/.X11-unix/X$opt{'-kill'}\n";
  644. unlink "/tmp/.X11-unix/X$opt{'-kill'}";
  645. }
  646. if (-e "/tmp/.X$opt{'-kill'}-lock") {
  647. print "Xvnc did not appear to shut down cleanly.";
  648. print " Removing /tmp/.X$opt{'-kill'}-lock\n";
  649. unlink "/tmp/.X$opt{'-kill'}-lock";
  650. }
  651. }
  652. unlink $pidFile;
  653. exit;
  654. }
  655. #
  656. # ParseOptions takes a list of possible options and a boolean indicating
  657. # whether the option has a value following, and sets up an associative array
  658. # %opt of the values of the options given on the command line. It removes all
  659. # the arguments it uses from @ARGV and returns them in @optArgs.
  660. #
  661. sub ParseOptions
  662. {
  663. local (@optval) = @_;
  664. local ($opt, @opts, %valFollows, @newargs);
  665. while (@optval) {
  666. $opt = shift(@optval);
  667. push(@opts,$opt);
  668. $valFollows{$opt} = shift(@optval);
  669. }
  670. @optArgs = ();
  671. %opt = ();
  672. arg: while (defined($arg = shift(@ARGV))) {
  673. foreach $opt (@opts) {
  674. if ($arg eq $opt) {
  675. push(@optArgs, $arg);
  676. if ($valFollows{$opt}) {
  677. if (@ARGV == 0) {
  678. &Usage();
  679. }
  680. $opt{$opt} = shift(@ARGV);
  681. push(@optArgs, $opt{$opt});
  682. } else {
  683. $opt{$opt} = 1;
  684. }
  685. next arg;
  686. }
  687. }
  688. push(@newargs,$arg);
  689. }
  690. @ARGV = @newargs;
  691. }
  692. # Routine to make sure we're operating in a sane environment.
  693. sub SanityCheck
  694. {
  695. local ($cmd);
  696. # Get the program name
  697. ($prog) = ($0 =~ m|([^/]+)$|);
  698. #
  699. # Check we have all the commands we'll need on the path.
  700. #
  701. cmd:
  702. foreach $cmd ("uname","xauth") {
  703. for (split(/:/,$ENV{PATH})) {
  704. if (-x "$_/$cmd") {
  705. next cmd;
  706. }
  707. }
  708. die "$prog: couldn't find \"$cmd\" on your PATH.\n";
  709. }
  710. if($exedir eq "") {
  711. cmd2:
  712. foreach $cmd ("Xvnc","vncpasswd") {
  713. for (split(/:/,$ENV{PATH})) {
  714. if (-x "$_/$cmd") {
  715. $vncClasses = "$_/../vnc/classes";
  716. next cmd2;
  717. }
  718. }
  719. die "$prog: couldn't find \"$cmd\" on your PATH.\n";
  720. }
  721. }
  722. else {
  723. cmd3:
  724. foreach $cmd ($exedir."Xvnc",$exedir."vncpasswd") {
  725. for (split(/:/,$ENV{PATH})) {
  726. if (-x "$cmd") {
  727. $vncClasses = $exedir."../vnc/classes";
  728. next cmd3;
  729. }
  730. }
  731. die "$prog: couldn't find \"$cmd\".\n";
  732. }
  733. }
  734. if (!defined($ENV{HOME})) {
  735. die "$prog: The HOME environment variable is not set.\n";
  736. }
  737. #
  738. # Find socket constants. 'use Socket' is a perl5-ism, so we wrap it in an
  739. # eval, and if it fails we try 'require "sys/socket.ph"'. If this fails,
  740. # we just guess at the values. If you find perl moaning here, just
  741. # hard-code the values of AF_INET and SOCK_STREAM. You can find these out
  742. # for your platform by looking in /usr/include/sys/socket.h and related
  743. # files.
  744. #
  745. chop($os = `uname`);
  746. chop($osrev = `uname -r`);
  747. eval 'use Socket';
  748. if ($@) {
  749. eval 'require "sys/socket.ph"';
  750. if ($@) {
  751. if (($os eq "SunOS") && ($osrev !~ /^4/)) {
  752. $AF_INET = 2;
  753. $SOCK_STREAM = 2;
  754. } else {
  755. $AF_INET = 2;
  756. $SOCK_STREAM = 1;
  757. }
  758. } else {
  759. $AF_INET = &AF_INET;
  760. $SOCK_STREAM = &SOCK_STREAM;
  761. }
  762. } else {
  763. $AF_INET = &AF_INET;
  764. $SOCK_STREAM = &SOCK_STREAM;
  765. }
  766. }